以编程方式向UIToolbar添加按钮

3
我将使用以下代码程序化地创建一个UIToolbar:
```swift ```
pickerTB = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
[self.view addSubview:pickerTB];

我应该如何在它上添加一个单独的按钮? 按钮需要显示“完成”,并且能够在以后调用方法。

3个回答

16

如果您想在 uitoolbar 的右侧添加“完成”按钮,则在“完成”按钮之前添加可伸缩按钮。

 UIBarButtonItem *flexButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
 UIBarButtonItem *doneButton =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneButton)];

 NSArray *itemsArray = [NSArray arrayWithObjects:flexButton, doneButton, nil];


 [toolbar setItems:itemsArray];

-(void)doneButton
{
}

// 更改工具栏样式

 [toolbar setBarStyle:UIBarStyleBlackTranslucent];

//更改工具栏按钮颜色

[doneButton setTintColor:[UIColor blackColor]];

如何实现半透明黑色? - Exothug
按钮仍然是蓝色的 :/ - Exothug
it is the one you provided - Exothug
太棒了。谢谢! :) - hacker_1989

2
pickerTB.items = [NSArray arrayWithObjects:[[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(done:)],nil];

1
这段代码将有助于在键盘或pickerview中添加按钮到UIToolbar。
例如: 如果您希望在pickerview的工具栏中插入“完成”按钮,则只需按照以下简单步骤操作。
第1步: 必须在“viewDidLoad”中包含此代码,以创建UIToolbar中的“完成”按钮。“textBoxText”是文本字段的名称。
    // create done button in toolbar.
    doneToolbar = UIToolbar(frame: CGRectMake(0, 0, self.view.frame.size.width, 50))
    doneToolbar.barStyle = UIBarStyle.Default
    doneToolbar.items =   [UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(FirstViewController.PickerDoneButtonTapped))]
    doneToolbar.sizeToFit()
    textBoxText.inputAccessoryView = doneToolbar

步骤2:编写“完成”按钮的功能,该按钮已包含在UIToolbar中。如果点击“完成”按钮,则PickerView必须禁用。

func PickerDoneButtonTapped()
{
    textBoxText.resignFirstResponder()
}

第三步:必须在“viewDidLoad”中调用该函数。
self.PickerDoneButtonTapped()

输出:

enter image description here


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