Remove mask from deselected tabs UITabBarItem Swif

2019-06-12 03:55发布

问题:

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

1) Here is how tab bar should look:

Please ignore orange button, that 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 a lot of times with tintColor, barTintColor and no success.

Also I tried to set 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 no success. Any thoughts at this issue ?

2) Second issue is about selectedImage property of UITabBarItem class. The width of image does not fit the tab. I changed between devices, and for every device the selected image is over the other tab, or does not fit the current tab.(I found a solution: to have the same image but with different width for every device. But for sure this is not a good solution)

Any kind of help will be fine! Many thanks

回答1:

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



回答2:

Here is a full example of how I managed both issues: https://github.com/AndreiBoariu/TabBarController

For first issue, I solved using this for loop in 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 extension of UIImage

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 second issue, check code from github ;)