Only image as UITabBarItem

后端 未结 9 2181
伪装坚强ぢ
伪装坚强ぢ 2021-02-01 05:29

I would only like to have an icon as the UITabBarItem and not the text underneath and I was wondering if this was possible, if so, how? TIA

9条回答
  •  Happy的楠姐
    2021-02-01 05:37

    You can use this Swift extension to define a new method tabBarItemShowingOnlyImage(), which will return any UITabBarItem modified to show only the image:

    // helper for creating an image-only UITabBarItem
    extension UITabBarItem {
        func tabBarItemShowingOnlyImage() -> UITabBarItem {
            // offset to center
            self.imageInsets = UIEdgeInsets(top:6,left:0,bottom:-6,right:0)
            // displace to hide
            self.setTitlePositionAdjustment(UIOffset(horizontal:0,vertical:30000))
            return self
        }
    }
    

    This extension builds from the advice offered in other comments.

    It hides the title by displacing it, rather than setting it to nil, because sometimes other objects like the view controller itself will set the title to some value after the tab bar item is initialized. It centers the image by using the imageInsets to offset it by 6pt, a value I get just from eyeballing it on an iPhone 6 running iOS8.3.

    I imagine that other devices and layout configurations might require a different offset correction, so a general solution would probably have to be more complex.

提交回复
热议问题