Moving UITabBarItem Image down?

2019-01-10 03:59发布

Normally on each tab of a UITabBar you have a small image and a title naming the tab. The image is positioned/centred towards the top of the tab to accommodate the title underneath. My question is: if you want to have a tabBar with just an image and no title is there a way to move the image down so it centers better within the tab?

I am using (see below) currently:

[tabBarItem setFinishedSelectedImage:tabSelected withFinishedUnselectedImage:tabUnselected];

but would prefer to use to larger image with no title, at the moment if I make the image bigger than about 70pixels@2x it starts edging off the top of the UITabBar whilst leaving a lot of unused space at the bottom.

8条回答
叛逆
2楼-- · 2019-01-10 04:16

Try adjusting tabBarItem's imageInsets (for moving the icon image) and setting the controllers title to nil (so no title is displayed). Put something like this to -init or -viewDidLoad method in view controller:

Objective-C

self.tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
self.title = nil;

Swift

self.tabBarItem.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0)
self.title = nil

UITabBarItem is a subclass of UIBarItem which has UIEdgeInsets imageInsets property. Play a little with the insets until it looks good (depending on your tabbar icon images)

查看更多
迷人小祖宗
3楼-- · 2019-01-10 04:16

You can do it via storyboard too. Select your tabbaritem, go to size inspector and assign the appropriate insets.

enter image description here

*Demonstrated on Xcode, Version 7.3.1 (7D1014)

查看更多
贪生不怕死
4楼-- · 2019-01-10 04:22

This worked for me

Swift 4

let array = tabBarController?.customizableViewControllers
for controller in array! {
    controller.tabBarItem.imageInsets = UIEdgeInsetsMake(5, 0, -5, 0)
}
查看更多
男人必须洒脱
5楼-- · 2019-01-10 04:23

For iOS 11 you need to override TraitCollection method apart from setting ImageInsets. Please add the method in your subclassed UITabBarController class

public override UITraitCollection TraitCollection {
 get {
  return UITraitCollection.FromHorizontalSizeClass(horizontalSizeClass: UIUserInterfaceSizeClass.Compact);
 }
}
查看更多
你好瞎i
6楼-- · 2019-01-10 04:24

If you're using Xamarin, this works:

screen.TabBarItem.ImageInsets = new UIEdgeInsets(5, 0, -5, 0);
screen.TabBarItem.Title = "";
查看更多
beautiful°
7楼-- · 2019-01-10 04:24

SWIFT 3.0

You can set image lnsets, set top,left,bottom and right according desing.

self.tabBarItem.imageInsets = UIEdgeInsets(top: 5, left: 0, bottom: 0, right: 0)
查看更多
登录 后发表回答