如何在工具栏右侧添加按钮?

14

我通过编程方式创建了一个工具栏:

UIToolbar *boolbar = [UIToolbar new];
    boolbar.barStyle = UIBarStyleDefault;
    boolbar.tintColor = [UIColor orangeColor];
    [boolbar sizeToFit];

然后添加了一个按钮:

UIBarButtonItem *cancelleftBarButton =[[UIBarButtonItem alloc]initWithTitle:@"OK" style:UIBarButtonItemStyleBordered target:self action:@selector(tapBackGround:)];

cancelleftBarButton.tintColor = [UIColor orangeColor];

NSArray *array = [NSArray arrayWithObjects:cancelleftBarButton, nil];
[boolbar setItems:array animated:YES];

然而,这个按钮只出现在工具栏的左侧。是否可能将其放置在工具栏的右侧?

输入图像描述

2个回答

36

这是在工具栏右侧添加UIBarButtonItem的方法。

UIBarButtonItem *leftButton = [[[UIBarButtonItem alloc] initWithTitle:@"Item" style:UIBarButtonItemStyleBordered target:self action:@selector(btnItem1Pressed:)] autorelease];

UIBarButtonItem *flex = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease];

UIBarButtonItem *rightButton = [[[UIBarButtonItem alloc] initWithTitle:@"Item" style:UIBarButtonItemStyleBordered target:self action:@selector(btnItem2Pressed:)] autorelease];

或者

如果你是从XIB尝试这么做的,那么...

插入一个标识为"flexible space"的项目。

输入图片描述


还可以查看这些链接https://dev59.com/7HRB5IYBdhLWcg3wgHar和https://dev59.com/K2025IYBdhLWcg3wZ1Ry - IronManGill

6

在Swift中

let btn1 = UIBarButtonItem(title: "Button 1", style: UIBarButtonItemStyle.Done, target: self, action: "btn1Pressed"
let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
let btn2 = UIBarButtonItem(title: "Button 2", style: UIBarButtonItemStyle.Done, target: self, action: "btn2Pressed")

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