简体   繁体   English

仅在单击完成按钮时,将UIPickerView选择添加到TextField

[英]Add UIPickerView selection to TextField only when clicking done button

I created a UIPickerView with a done button in a toolbar. 我用工具栏中的完成按钮创建了一个UIPickerView。 I would like to accomplish the following: 我想完成以下工作:

User selects a category in the UIPickerView and then taps the "done" button. 用户在UIPickerView中选择一个类别,然后点击“完成”按钮。 Result should be that the UIPickerView and the Toolbar disappears and the Category TextField gets updated with the user's selection. 结果应该是UIPickerView和工具栏消失了,并且类别TextField已根​​据用户的选择进行了更新。 I almost have everything right. 我几乎没事了。 The PickerView and the Toolbar disappear when the done button gets tapped. 点击完成按钮时,PickerView和工具栏消失。 But the Textfield gets updated even before I tap the button. 但是,甚至在我点击按钮之前,Textfield都会更新。 But I want the textfield only updated when the done button gets tapped. 但是我只想在完成按钮被点击时才更新文本字段。

Can anyone point me in the right direction where I have my error? 谁能指出我犯错误的正确方向? Thanks 谢谢

that is the code I used: 那就是我使用的代码:

- (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];

Try creating an instance variable, for example 尝试创建一个实例变量,例如

NSInteger selectedRow;

In the pickerView:didSelectRow:inComponent: method, replace the line you have with pickerView:didSelectRow:inComponent:方法中,将您的行替换为

selectedRow = row;

And in the doneButtonTapped: method, add the line 然后在doneButtonTapped:方法中,添加以下行

self.textFieldCategory.text = _pickerData[selectedRow];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM