31

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 ?

pkamb
  • 33,281
  • 23
  • 160
  • 191
tristaf
  • 329
  • 1
  • 4
  • 6

6 Answers6

61

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.

Kevin Sylvestre
  • 37,288
  • 33
  • 152
  • 232
  • 2
    Is it possible to update the label in realtime while the picker view is scrolling? I mean it takes time. But the requirement is to get it to work as it works in Android.(Which is flawless) – Ritesh.mlk Sep 01 '18 at 11:26
  • Old question, but my advice here is, don't try to force iOS to be Android as users of either platform may be used to different functionality. Neither is 'right' or 'wrong', just different. – Ash Jul 16 '20 at 13:27
6

UIPickerViewDelegate has pickerView:didSelectRow:inComponent:

gammelgul
  • 3,450
  • 1
  • 20
  • 16
2

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
            }        
}
Gian
  • 31
  • 5
1

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.

0

You have to use picker view delegate method:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
}
aturan23
  • 4,798
  • 4
  • 28
  • 52
Haya Hashmat
  • 137
  • 10
0
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.

incredever
  • 231
  • 1
  • 2
  • 11