标签:
UIPickerView控件在给 用户选择某些特定的数据时经常使用到,这里演示一个简单的选择数据,显示在UITextField输入框里,把UIPickerView作为输入 View,用Toolbar作为选定数据的按钮。和其他UITableView控件相似,UIPickerView也需要数据源。
我们要实现的效果如下:
下面开始使用的步骤。
1、打开XCode,新建一个Single View Application ,命名为PickerViewDemo,Company Identifier 为:com.company.program
2、拖放控件
2.1、拖放一个UIPickerView,放置在View的最下方
2.2、拖放一个Toolbar控件,放置在View的外面,让它不属于View的子控件,并把item命名为“完成”,效果如下:
2.3 放置一个Flexible Space Bar Button Item 撑开
2.4 放一个UITextField,用来显示选择的数据
3、创建映射
在ViewController.xib文件里,按住Control键,选择各个控件,拖拽到 ViewController.h文件里,生成以下变量代码
- #import <UIKit/UIKit.h>
-
- @interface ViewController : UIViewController
- {
- NSArray *pickerArray;
- }
- - (IBAction)selectButton:(id)sender;
- @property (strong, nonatomic) IBOutlet UIToolbar *doneToolbar;
-
- @property (strong, nonatomic) IBOutlet UIPickerView *selectPicker;
- @property (strong, nonatomic) IBOutlet UITextField *textField;
- @end
4、实现数据源和协议
ViewController.h文件里实现
<UIPickerViewDelegate, UITextFieldDelegate,UIPickerViewDataSource>
- #import <UIKit/UIKit.h>
-
- @interface ViewController : UIViewController<UIPickerViewDelegate, UITextFieldDelegate,UIPickerViewDataSource>
- {
- NSArray *pickerArray;
- }
- - (IBAction)selectButton:(id)sender;
- @property (strong, nonatomic) IBOutlet UIToolbar *doneToolbar;
-
- @property (strong, nonatomic) IBOutlet UIPickerView *selectPicker;
- @property (strong, nonatomic) IBOutlet UITextField *textField;
- @end
ViewController.m文件
- -(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
- return 1;
- }
- -(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
- return [pickerArray count];
- }
- -(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
- return [pickerArray objectAtIndex:row];
- }
-
- -(void)textFieldDidEndEditing:(UITextField *)textField{
- NSInteger row = [selectPicker selectedRowInComponent:0];
- self.textField.text = [pickerArray objectAtIndex:row];
- }
上面numberOfComponentsInPickerView返回有几个PickerView ,
textFieldDidEndEditing这个在textField结束编辑时,显示PickerView选择中的数据。
Toolbar 的item的完成按钮
- - (IBAction)selectButton:(id)sender {
- [textField endEditing:YES];
- }
5、初始化
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- pickerArray = [NSArray arrayWithObjects:@"动物",@"植物",@"石头",@"天空", nil];
- textField.inputView = selectPicker;
- textField.inputAccessoryView = doneToolbar;
- textField.delegate = self;
- selectPicker.delegate = self;
- selectPicker.dataSource = self;
- selectPicker.frame = CGRectMake(0, [[UIScreen mainScreen] bounds].size.height-64-216, [[UIScreen mainScreen] bounds].size.width, 216);
-
- }
代码解释:
设置委托
textField.delegate =self;
selectPicker.delegate =self;
selectPicker.dataSource =self;
隐藏UIPickerView
selectPicker.frame =CGRectMake(0,[[UIScreen mainScreen] bounds].size.height-64,[[UIScreen mainScreen] bounds].size.width, 216);
运行:
iOS UIPickerView的简单使用
标签:
原文地址:http://www.cnblogs.com/huangzs/p/4568973.html