2013-07-17 79 views
3

我编程方式创建与此代码UIToolbar:编程添加按钮UIToolbar

pickerTB = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)]; 
[self.view addSubview:pickerTB]; 

如何添加一个单一的按钮呢?它需要说“完成”,并且该按钮必须能够稍后调用方法。

回答

16

试试这个,如果你想添加的uitoolbar的右侧DONE按钮,然后添加灵活键之前完成按钮

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]]; 
+0

怎么办半透明黑色? – Exothug

+0

检查我编辑的答案 – Kalpesh

+0

按钮仍然是蓝色:/ – Exothug

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

这段代码对于将按钮添加到存在于键盘或pickerview中的UIToolbar非常有用。

例如: 如果您希望在拾取器视图的工具栏中插入“完成”按钮。你只需要按照如下简单的步骤。

步骤1: 必须在“viewDidLoad”中包含此代码才能在UIToolbar中创建“完成”按钮。 “textBoxText”是文本字段的名称。

步骤2: 码已列入UIToolbar“完成”按钮的功能。我已经指出,如果点击“完成”按钮,PickerView必须禁用。

func PickerDoneButtonTapped() 
{ 
    textBoxText.resignFirstResponder() 
} 

第3步: 要调用的函数 “viewDidLoad中”

self.PickerDoneButtonTapped() 

输出:

enter image description here

+0

真是一个很好的例子 –