UITabBar not showing selected item images in ios 7

后端 未结 20 1881
我在风中等你
我在风中等你 2020-11-29 18:36

The icons show fine in ios 6 but not in ios 7. I\'m setting the selected state in the viewController viewDidLoad method. When the user selects a tab bar item the image disap

20条回答
  •  无人及你
    2020-11-29 19:04

    Here is a Swift solution for Swift-Guys :)

    class CustomTabBar: UITabBar {
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
    
            let btnNames = ["Title1", "Title2", "Title3", "Title4"]
    
            for (item, name) in zip(items!, btnNames) {
                item.image = UIImage(named: "bar\(name)Btn")?.imageWithRenderingMode(.AlwaysOriginal)
                item.selectedImage = UIImage(named: "bar\(name)SelectedBtn")?.imageWithRenderingMode(.AlwaysOriginal)
                item.title = name
                item.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blackColor()], forState: .Normal)
                item.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.redColor()], forState: .Selected)
            }
        }
    
    }
    

    What is exactly going on here:

    • Make array of btn titles and consider image file names to match them
    • Make For loop over tab bar items and just created btn titles array
    • Set barButtonItem's image and its selectedImage from the array
    • Set title text from the array
    • Set title text color for states .Normal and .Selected

    Setting text colors part is important if you don't want to keep the item's title color gray for .Normal and blue for .Selected, as it is by default. This is often actual when you consider custom images for tab bar items.

提交回复
热议问题