在UIToolbar中居中显示UIBarButtonItem并添加自定义文本

4

我需要在工具栏的中心添加一个按钮。我已经成功地将按钮添加到工具栏上了。我的问题如下:

1.) 我需要将这个按钮居中。它应该在工具栏的中心。

2.) 在刷新按钮图像显示后,我需要有一段文本。

toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0 , 320 , 60)];

    NSMutableArray* button = [[NSMutableArray alloc] initWithCapacity:1];

    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshButtonAction:)];

    [button addObject:barButton];

    [toolBar setItems:button animated:NO];

    [self.view addSubview:toolBar];
2个回答

17

1. 在工具栏项目数组中,在您的条形按钮之前和之后添加灵活的间隔符:

toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0 , 320 , 60)];

UIBarButtonItem *flexibleSpace =  [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshButtonAction:)];

NSArray *toolbarItems = [NSArray arrayWithObjects:flexibleSpace, barButton, flexibleSpace];

[toolBar setItems:toolbarItems animated:NO];

[self.view addSubview:toolBar];

在Interface Builder中配置工具栏要容易得多。如果您的视图控制器位于UINavigationController堆栈中,仍然可以使用IB创建一个UIBarButtonItem输出集合,并在-viewDidLoad中设置self.toolbarItems

2. 要在工具栏中获取自定义内容,您可以创建一个带有自定义视图的工具栏按钮项:

UIView *customView = <# anything, could be a UILabel #>;
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:customView];

我是iOS的新手。这是关于“答案(2)”的问题。你说的“<# anything, could be a UILabel #>”是指类似于“UIView *customView = [UILabel alloc] initWithRect:....]”这样的东西吗?(抱歉,我是个新手) - sharon
是的,抱歉。UILabelUIView 的子类,所以如果符合您的需求,请创建一个并使用它。如果需要更复杂的内容,请构建自己的自定义 UIView。您也可以在 IB 中完成这个操作 ;) - Ryder Mackay
问题在于我需要 UIBarButtonSystemItemRefresh 后面跟着一段文本。那么你的方法能行吗?因为我将使用 initWithBarButtonSystemItem 来添加“刷新”图标,然后我无法使用 initWithCustomView 来添加包含标签的 UIView - sharon
系统项目实际上无法自定义--您需要创建第二个项目来显示文本,或者使用一个带有自己刷新按钮和文本的自定义项目。 - Ryder Mackay

1

我知道这可以在IB中完成,但我相信如果你想要居中一个按钮,你需要在两侧添加一个固定或可伸缩的空间按钮来保持你的按钮在中间。如果你只是用代码来实现...尝试将你的按钮夹在这两个空间按钮之间。


是的,我必须用代码完成它 :(。你能给我展示一个演示如何实现这个的样例代码吗? - sharon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接