Remove mask from unselected tabs UITabBarItem Swift

I am trying to implement a UITabBarController with 2 UITabBarItems . I added a TabBarController to the storyboard. I almost did it, but still I am blocked by two important issues:

1) Here is what the tab bar looks like: enter image description here

Please ignore the orange button, which is not a tabItem. So I put 2 tabItems, and I want to keep white images for both tabs, even if one of them is selected. I checked tintColor , barTintColor many times and did not succeed.

Also I tried setting tabBarItem in ViewController:

 override func awakeFromNib() { super.awakeFromNib() let imgHome = UIImage(named: "btnHome")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) let imgProfile = UIImage(named: "btnProfile")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) let imgSelectedTab = UIImage(named: "selectedTab_imgBackground")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) tabBarItem = UITabBarItem(title: nil, image: imgProfile, selectedImage: imgSelectedTab) } 

but without success. Any thoughts on this issue?

2) The second question concerns the selectedImage property of the UITabBarItem class. image width does not match tab. I switched between devices, and for each device, the selected image moved through another tab or does not correspond to the current tab. (I found a solution: to have the same image, but with a different width for each device. Not a good solution)

second tab selectedfirst tab selected

Any help would be ok! Thank you very much

0
source share
2 answers

Here is a complete example of how I managed to solve both problems: https://github.com/AndreiBoariu/TabBarController

For the first problem, I decided to use this for loop in the UITabBarController class:

 for item in tabBar.items as! [UITabBarItem] { if let image = item.image { item.image = image.imageWithColor(UIColor.whiteColor()).imageWithRenderingMode(.AlwaysOriginal) } } 

and here is the UIImage extension

 public extension UIImage { func imageWithColor(tintColor: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) let context = UIGraphicsGetCurrentContext() as CGContextRef CGContextTranslateCTM(context, 0, self.size.height) CGContextScaleCTM(context, 1.0, -1.0); CGContextSetBlendMode(context, kCGBlendModeNormal) let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect CGContextClipToMask(context, rect, self.CGImage) tintColor.setFill() CGContextFillRect(context, rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage UIGraphicsEndImageContext() return newImage } } 

For the second problem , check the code from github;)

0
source

You need to change the rendering mode to UIImageRenderingModeAlwaysOriginal instead of automatic.

0
source

Source: https://habr.com/ru/post/978559/


All Articles