setSelectionIndicatorImage is of wrong size for iphone 6 and iPhone 6+

前端 未结 2 1600
栀梦
栀梦 2021-02-06 08:16

I am using following method to set selection indicator for selected tab bar item. It works well for iPhone 4/4s/5/5s but not in iphone 6/6+.

[[UITabBar appearan         


        
2条回答
  •  遇见更好的自我
    2021-02-06 08:48

    Here is my auto-adjusting UITabBarController subclass. Just provide an image and it will adjust to all known iPhones and iPads. It will also update the size whenever the trait collection changes so it supports all the new iPad features and rotation.

    import UIKit
    
    class TabBarController: UITabBarController {
        override func viewWillAppear(animated: Bool) {
            super.viewWillAppear(animated)
    
            updateSelectionIndicatorImage()
        }
    
        override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
            super.traitCollectionDidChange(previousTraitCollection)
    
            updateSelectionIndicatorImage()
        }
    
        func updateSelectionIndicatorImage() {
            let width = CGRectGetWidth(tabBar.bounds) > 420 ? 420 : CGRectGetWidth(tabBar.bounds)
            var selectionImage = UIImage(named: "TabSelectionIndicator")
            let tabSize = CGSizeMake(width/5, 49)
    
            UIGraphicsBeginImageContext(tabSize)
            selectionImage?.drawInRect(CGRectMake(0, 0, tabSize.width, tabSize.height))
            selectionImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    
            tabBar.selectionIndicatorImage = selectionImage
        }
    }
    

提交回复
热议问题