30
votes

I want to detect changes of UIPickerView value.

If UIPickerView respond to addTarget I used a code like this:

-(void) valueChange:(id)sender {
change = YES;

} 

UIPickerView *questionPicker = [[UIPickerView alloc] init]; 
[questionPicker addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];

How can I do same things but in a correct way ?

6

6 Answers

61
votes

If you look at the UIPickerViewDelegate it has:

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component

Simply set your picker views delegate and implement this.

6
votes

UIPickerViewDelegate has pickerView:didSelectRow:inComponent:

1
votes

Better override this function

public override func selectedRow(inComponent component: Int) -> Int {
  let index = super.selectedRow(inComponent: component)
  //call closure or delegate as you want
  return index
}

in UIPickerView class to observe changing in realtime.

1
votes

Swift 4: Implement picker view delegates:

optional public func pickerView(_ pickerView: UIPickerView, titleForRow row: 
   Int, forComponent component: Int) -> String?

Example:

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, 
forComponent component: Int) -> String? {
            let value = dummyListArray[row]
            if value == "someText"{
              //Perform Action
            }
            return value
}

Or

optional public func pickerView(_ pickerView: UIPickerView, didSelectRow row: 
   Int, inComponent component: Int)

Example:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, 
inComponent component: Int) {
            let value = dummyListArray[row]
            if value == "someText"{
              //Perform Action
            }        
}
0
votes
func pickerView(UIPickerView, didSelectRow: Int, inComponent: Int)

Called by the picker view when the user selects a row in a component.

That allows for instance to update a textfield when selection change, just on the release of a finger.

0
votes

You have to use picker view delegate method:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
}