好长时间不用,很多技能恢复了初始化状态,今天简单的复习了一下UIPickerView,进行了如下总结,希望可以帮到初学者:
使用步骤:
- 初始化textField并设置代理
- 在代理方法 textFieldDidBeginEditing: 中初始化UIPickerView
- 通过触发按钮隐藏UIPickerView,并将UIPickerView选择后内容赋给textField.text
代码
(1)初始化
- (void)viewDidLoad {
[super viewDidLoad];
self.sexTF = [[UITextField alloc] initWithFrame:CGRectMake(50, 80, 100, 40)];
self.sexTF.delegate = self;
self.sexTF.borderStyle = UITextBorderStyleLine;
self.sexTF.textColor = [UIColor blackColor];
self.sexTF.textAlignment = NSTextAlignmentLeft;
self.sexTF.font = [UIFont systemFontOfSize:16];
[self.view addSubview:self.sexTF];
_sexArr = @[@"性别:男",@"性别:女"];
}
(2) 实现UITextFieldDelegate
#pragma - mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
//隐藏键盘,避免遮挡pickerView
[self.sexTF resignFirstResponder];
[self showSexPickerView];
}
(3)初始化PickerView,并实现pickerView相关代理
- (void)showSexPickerView{
//控制pickerView隐藏按钮
UIButton *donePickerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
donePickerBtn.frame = CGRectMake((self.view.frame.size.width-100)/2.0, self.view.frame.size.height - 50, 100, 40);
donePickerBtn.titleLabel.font = [UIFont systemFontOfSize:18];
[donePickerBtn setTitle:@"确定" forState:UIControlStateNormal];
[donePickerBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[donePickerBtn addTarget:self action:@selector(hideSexPickerView) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:donePickerBtn];
//pickerView
self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 150, self.view.frame.size.width, 200)];
self.pickerView.showsSelectionIndicator=YES;
self.pickerView.delegate=self;
self.pickerView.dataSource=self;
self.pickerView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.8];
self.pickerView.showsSelectionIndicator = YES;
[self.view addSubview:self.pickerView];
}
#pragma - mark - UIPickerViewDelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
return _sexArr[row];
}
#pragma - mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return _sexArr.count;
}
(4)隐藏pickerView并将选中内容赋值给textField
- (void)hideSexPickerView{
NSInteger row = [self.pickerView selectedRowInComponent:0];
self.sexTF.text = [_sexArr objectAtIndex:row];
[self.pickerView removeFromSuperview];
}
实现结果: