ios - 在导航栏项目之间创建空白区域?

标签 ios uinavigationbar uibarbuttonitem

我花了几个小时试图解决这个问题,直到没完没了。我的最后一个选择是只创建空白标签来创建空间,但我觉得它们是一种更简洁的方法。

基本上我有三个按钮,我们试图在它们之间创建固定的空间以保持整洁。每个按钮都是以编程方式添加的。

我找到了这段代码:

UIBarButtonItem *fixedItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
fixedItem.width = 20.0f; // or whatever you want

( Source )

但是如何将这段代码分配给某个按钮呢?

最佳答案

您可能感到困惑。您没有将此代码分配给按钮。该代码创建了一个 UIBarButtonSystemItemFixedSpace 类型的按钮。所以,按照你链接到的答案说的去做。创建固定且灵活的 UIBarButtonItem(以及您拥有的其他按钮),然后将它们设置在导航栏上。在这种情况下,它们将出现在导航栏的左上角区域(通过 leftBarButtonItems):

// Create "Normal" buttons items:
UIBarButtonItem *button1 = [[UIBarButtonItem alloc] initWithTitle:@"1" style:UIBarButtonItemStylePlain target:Nil action:nil];
UIBarButtonItem *button2 = [[UIBarButtonItem alloc] initWithTitle:@"2" style:UIBarButtonItemStylePlain target:Nil action:nil];    
UIBarButtonItem *button3 = [[UIBarButtonItem alloc] initWithTitle:@"3" style:UIBarButtonItemStylePlain target:Nil action:nil];

// Create "Spacer" bar button items 
UIBarButtonItem *fixedItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
fixedItem.width = 20.0f; // or whatever you want
UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

self.navigationItem.leftBarButtonItems = @[button1, fixedItem, button2, flexibleItem, button3];

此外,如果您有一个工具栏,您可以使用工具栏的 items 属性:

self.toolbar.items = @[button1, fixedItem, button2, flexibleItem, button3];

关于ios - 在导航栏项目之间创建空白区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22211516/

相关文章:

iphone - UIBarButtonItem 偏移量

ios - 如何将字典作为参数附加到 URL?

ios - PAN 与 Linux、iOS、蓝牙、Bonjour、GameKit——可能吗?

ios - 在没有单元格的情况下为 UICollectionView 启用弹跳/滚动

ios - 导航栏错误

iphone - 动画启用 UIBarButtonItem?

ios - 自动布局 iOS 11 工具栏 UIBarButtonItem 与 customView

ios - 我怎样才能在另一个执行 segue 的 View Controller 上获得按钮标题?

ios - 导航栏中的 UISearchBar

ios - 在 Interface Builder 中更改导航栏标题字体