xcode 如何更改 UITabBarItem 的宽度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6888389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change the width of UITabBarItem?
提问by demon9733
How to change the width of UITabBarItem?
如何更改 UITabBarItem 的宽度?
I have an item with the title, that is wider than default item width. How can I fix it?
我有一个带有标题的项目,它比默认项目宽度宽。我该如何解决?
采纳答案by rich
I just searched through the documentation and saw no method for adjusting the UITabBarItem's width.
我只是搜索了文档,没有看到调整 UITabBarItem 宽度的方法。
A possible solution would be to place a view within the tab bar controller to load a custom UITabBarItem, that is the proper width.
一种可能的解决方案是在选项卡栏控制器中放置一个视图以加载自定义 UITabBarItem,即适当的宽度。
回答by jomafer
Solution for iOS7 and greater versions:
iOS7及以上版本解决方案:
A new property has been introduced for UITabBar: itemWidth.
为 UITabBar 引入了一个新属性:itemWidth。
Set the itemWidth to a positive value to be used as the width for tab bar items when they are positioned as a centered group (as opposed to filling the tab bar). Default of 0 or values less than 0 will be interpreted as a system-defined width.
将 itemWidth 设置为正值,当它们被定位为居中组(而不是填充标签栏)时,将用作标签栏项目的宽度。默认值 0 或小于 0 的值将被解释为系统定义的宽度。
@property(nonatomic) CGFloat itemWidth NS_AVAILABLE_IOS(7_0) UI_APPEARANCE_SELECTOR;
So you can do this in your AppDelegate:
所以你可以在你的 AppDelegate 中做到这一点:
[[UITabBar appearance] setItemWidth:WIDTH];
If you want to fill the whole UITabBar:
如果要填充整个 UITabBar:
[[UITabBar appearance] setItemWidth:self.window.frame.size.width/NUMBER_OF_ITEMS];
回答by MrTJ
You can change the spacing (and width) of the tab bar items by subclassing UITabBar and overriding its layoutSubviews method. You will find all tab bar buttons in the self.subViews array. Their class is the non-public UITabBarButton but they inherit from UIControl so you can identify all tab bar buttons checking if they are kind of UIControl class. Then all you need is to change the frame of the tab bar buttons.
您可以通过继承 UITabBar 并覆盖其 layoutSubviews 方法来更改选项卡栏项的间距(和宽度)。您将在 self.subViews 数组中找到所有标签栏按钮。它们的类是非公共的 UITabBarButton,但它们继承自 UIControl,因此您可以识别所有选项卡栏按钮,检查它们是否属于 UIControl 类。然后你所需要的就是改变标签栏按钮的框架。
回答by rad182
Found easier solution for swift if you subclass the UITabBarController this will autofill the tab bar items evenly
如果您将 UITabBarController 子类化,则为 swift 找到更简单的解决方案,这将均匀地自动填充选项卡栏项目
self.tabBar.itemPositioning = .fill
回答by Gurjinder Singh
Swift 5
斯威夫特 5
UITabBar().itemWidth = self.window!.frame.size.width/5