简体   繁体   English

如何检测 UIPickerView 上的变化?

[英]How to detect changes on UIPickerView?

I want to detect changes of UIPickerView value.我想检测 UIPickerView 值的变化。

If UIPickerView respond to addTarget I used a code like this:如果 UIPickerView 响应 addTarget 我使用了这样的代码:

-(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 ?我怎样才能以正确的方式做同样的事情?

If you look at the UIPickerViewDelegate it has:如果你看看UIPickerViewDelegate它有:

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

Simply set your picker views delegate and implement this.只需设置您的选择器视图委托并实现它。

UIPickerViewDelegatepickerView: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.UIPickerView类中实时观察变化。

Swift 4: Implement picker view delegates: Swift 4:实现选择器视图委托:

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

You have to use picker view delegate method:您必须使用选择器视图委托方法:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
}
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.例如,这允许在选择更改时更新文本字段,只需松开手指即可。

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

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