开发者

How to detect changes on UIPickerView?

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:UIC开发者_如何学运维ontrolEventValueChanged];

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


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.


UIPickerViewDelegate has pickerView:didSelectRow:inComponent:


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.


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
            }        
}


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.


You have to use picker view delegate method:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜