仅在单击完成按钮时将 UIPickerView 选择添加到 TextField
Posted
技术标签:
【中文标题】仅在单击完成按钮时将 UIPickerView 选择添加到 TextField【英文标题】:Add UIPickerView selection to TextField only when clicking done button 【发布时间】:2015-03-24 21:25:43 【问题描述】:我在工具栏中创建了一个带有完成按钮的 UIPickerView。我想完成以下工作:
用户在 UIPickerView 中选择一个类别,然后点击“完成”按钮。结果应该是 UIPickerView 和 Toolbar 消失,并且 Category TextField 会随着用户的选择而更新。我几乎把一切都做好了。当点击完成按钮时,PickerView 和工具栏会消失。但是即使在我点击按钮之前,文本字段也会更新。但我希望仅在点击完成按钮时更新文本字段。
谁能指出我有错误的正确方向?谢谢
这是我使用的代码:
- (void)viewDidLoad
[super viewDidLoad];
// Do any additional setup after loading the view.
//disable saveButton
[_saveButton setEnabled:NO];
[self.picker removeFromSuperview];
[self.pickerToolbar removeFromSuperview];
//Initialize Data
_pickerData = @[@"Item 1", @"Item 2", @"Item 3", @"Item 4"];
//Connect Data
self.picker.dataSource = self;
self.picker.delegate = self;
_textFieldCategory.inputView = _picker;
_textFieldCategory.inputAccessoryView = _pickerToolbar;
- (void)didReceiveMemoryWarning
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
// The number of columns of data
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
return 1;
// The number of rows of data
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
return _pickerData.count;
// The data to return for the row and component (column) that's being passed in
- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
return _pickerData[row];
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
self.textFieldCategory.text = _pickerData[row];
- (IBAction)doneButtonTapped:(id)sender
[self.picker removeFromSuperview];
[self.pickerToolbar removeFromSuperview];
【问题讨论】:
【参考方案1】:尝试创建一个实例变量,例如
NSInteger selectedRow;
在pickerView:didSelectRow:inComponent:
方法中,将您拥有的行替换为
selectedRow = row;
然后在doneButtonTapped:
方法中,添加一行
self.textFieldCategory.text = _pickerData[selectedRow];
【讨论】:
完成!抱歉,系统提示我需要等待 3 分钟才能查看!以上是关于仅在单击完成按钮时将 UIPickerView 选择添加到 TextField的主要内容,如果未能解决你的问题,请参考以下文章
UIPickerView 的 selectedRowInComponent 仅在旋转且未选中时返回随机行。怎么了?