2017-05-03 3 views
0

私は3つのタブを持つUITabBarを持っています。今、私は割り当てたい、または関連するselectionIndicatorImageに1つのタブの完全な幅を塗りつぶすことができます現在、私は、タブが選択されている場合、境界線を持っている。左側のタブには、次のスクリーンショットに示し同様:backgroundColorのを持つためにSwift 3 - selectionIndicatorImageのUITabBarItemの全幅

var activeItemBackground:UIColor = UIColor.white { 
    didSet { 

     let numberOfItems = CGFloat((items!.count)) 

     let tabBarItemSize = CGSize(width: frame.width/numberOfItems, 
            height: frame.height) 

     selectionIndicatorImage = UIImage.imageWithColor(color: activeItemBackground, 
            size: tabBarItemSize).resizableImage(withCapInsets: .zero) 

     frame.size.width = frame.width + 4 
     frame.origin.x = -2 


    } 
} 

そしてUIImage-拡張子:

border

は、私は新しいプロパティとUITabBarのサブクラスを作りました画像:

extension UIImage 
{ 
    class func imageWithColor(color: UIColor, size: CGSize) -> UIImage 
    { 
     let rect: CGRect = CGRect(x: 0, y: 0, width: size.width, height: size.height) 
     UIGraphicsBeginImageContextWithOptions(size, false, 0) 
     color.setFill() 
     UIRectFill(rect) 
     let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! 
     UIGraphicsEndImageContext() 
     return image 
    } 
} 

私はこの問題について多くのことを読んでいますが、残念ながらそれを動作させることはできません。私のコードに何かがありませんか?

答えて

1

私はあなたがカップルの余分な手順を取っていると思います...

あなたは、タブバー項目の正確なサイズを計算し、そのサイズの画像を作成するので、あなたは必要はありませんされています.resizableImage部分。

正確なサイズに設定しているため、タブバーフレームのサイズを変更する必要もありません。

これは、(あなたの.imageWithColor FUNCを使用して)私のテストでは正常に動作する表示されます。そして、最初のVCののviewDidLoadで

class MyTabBar: UITabBar { 

    var activeItemBackground:UIColor = UIColor.white { 
     didSet { 

      let numberOfItems = CGFloat((items!.count)) 

      let tabBarItemSize = CGSize(width: frame.width/numberOfItems, 
             height: frame.height) 

      selectionIndicatorImage = UIImage.imageWithColor(color: activeItemBackground, 
                  size: tabBarItemSize) 

     } 
    } 

} 

if let tb = self.tabBarController?.tabBar as? MyTabBar { 
     tb.activeItemBackground = UIColor.red 
    } 
+0

感謝を。あなたのコードは正常に動作します。私の不具合は私のコードでactiveItemBackgroundを一番早く設定したため、最後のコードスニペットでもありました。 –