我一直在试图找到最后一周的解决方案,在尝试我可以找到或想到的所有可能的解决方案后,我都没有运气.我发现和尝试的每个解决方案都没有工作,或者已经过时了.
我在UITabBarController中的UITabBar中有5个UITabBarItem.当选择UITabBarItem时,我想更改背景颜色,当然,当所选项目更改时,它将会更改.
我在Xcode 6.3.1中使用Swift和iOS SDK 8.3.如果您只能在Objective-C中答案,那么任何答案都将有所帮助!谢谢大家提前,我真的很感激!
编辑:这是我想要做的一个视觉示例.
解决方法
在您的tabBarController中,您可以设置默认的UITabBar tintColor,barTintColor,selectionIndicatorImage(在这里作弊)和renderingMode的图像,请参阅以下注释:
class MyTabBarController: UITabBarController,UINavigationControllerDelegate { ... override func viewDidLoad() { ... // Sets the default color of the icon of the selected UITabBarItem and Title UITabBar.appearance().tintColor = UIColor.redColor() // Sets the default color of the background of the UITabBar UITabBar.appearance().barTintColor = UIColor.blackColor() // Sets the background color of the selected UITabBarItem (using and plain colored UIImage with the width = 1/5 of the tabBar (if you have 5 items) and the height of the tabBar) UITabBar.appearance().selectionIndicatorImage = UIImage().makeImageWithColorAndSize(UIColor.blueColor(),size: CGSizeMake(tabBar.frame.width/5,tabBar.frame.height)) // Uses the original colors for your images,so they aren't not rendered as grey automatically. for item in self.tabBar.items as! [UITabBarItem] { if let image = item.image { item.image = image.imageWithRenderingMode(.AlwaysOriginal) } } } ... }
并且您将需要扩展UIImage类以使您需要的大小为纯色图像:
extension UIImage { func makeImageWithColorAndSize(color: UIColor,size: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size,false,0) color.setFill() UIRectFill(CGRectMake(0,size.width,size.height)) var image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }