调整 UIToolbar 的大小以适应其项目?
我正在尝试找出一种干净的方法来使 UIToolbar
的宽度仅满足其包含的项目所需的宽度。有没有办法:
- 配置
UIToolbar
以在其项目更改时自动调整其宽度? - 以编程方式确定项目所需的最小宽度,然后可以使用它来设置
UIToolbar
的框架?
由于项目之间的间距以及 UIBarButtonItem 不是 UIView 子类这一事实,我无法弄清楚这一点。
I'm trying to figure out a clean way to make a UIToolbar
only as wide as it needs to be to fit the items that it contains. Is there a way to either:
- Configure the
UIToolbar
to adjust its width automatically as its items are changed? - Programatically determine the minimum width required by the items, which can then be used to set the
UIToolbar
's frame?
I haven't been able to figure this out due to the spacing between the items and the fact that UIBarButtonItem
s are not UIView
subclasses.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在尝试了其他答案中的一些建议后,除非我使用自定义视图,或者除非所有内容都已加载,否则这些建议不起作用,我终于找到了一种根据其项目设置工具栏宽度的方法:
您需要覆盖 UIToolbar - setItems: 或以其他方式检测更改的按钮以自动调整大小。
我已将此功能包含在我的重构库 es_ios_utils 中,以设置导航项的右侧项有多个按钮。在前面的链接中,请参阅
UIToolbar +toolbarWithItems:
和UINavigationItem -setRightBarButtonItems
。After trying some suggestions from other answers that did not work unless I used custom views, or unless everything was loaded, I finally arrived at a way to set the toolbar width based on its items:
You'll need to override
UIToolbar -setItems:
or otherwise detect changed buttons to autoresize.I have included this feature in my refactoring library, es_ios_utils, to set a navigation item's right item with multiple buttons. In the preceding link, see
UIToolbar +toolbarWithItems:
andUINavigationItem -setRightBarButtonItems
.我刚刚检查了文档,看起来像 UIBarButtonItems,即使它们不是 UIView 子类,它们也有一个属性 宽度。我自己没有尝试过,但我认为您可以对每个项目(包括灵活项目)的宽度求和,并获取工具栏的宽度。
希望有帮助! ;)
I just checked the documentation and seems like UIBarButtonItems, even though they are not UIView subclasses, they have an attribute width. I didn't try it myself, but I think you could sum each item's width, including the flexible item, and get the width for your toolbar.
Hope it helps! ;)
Swift 3、4 更新
我有一个工具栏,其中带有用图像启动的 barButtonItem。我需要做的就是计算图像的总宽度加上间隔(边距)。
默认情况下,边距宽度为 11。代码将是:
Swift 3, 4 update
I have a toolbar with barButtonItem initiated with image. All I need to do is to calculate the total width of the images plus the intervals (margin.)
Margin is by default 11 in width. The code will be: