【问题标题】:How to detect changes on UIPickerView?如何检测 UIPickerView 上的变化?
【发布时间】:2011-02-03 16:20:13
【问题描述】:

我想检测 UIPickerView 值的变化。

如果 UIPickerView 响应 addTarget 我使用了这样的代码:

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

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

我怎样才能以正确的方式做同样的事情?

【问题讨论】:

    标签: ios objective-c swift uipickerview


    【解决方案1】:

    您必须使用选择器视图委托方法:

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

    【讨论】:

      【解决方案2】:
      func pickerView(UIPickerView, didSelectRow: Int, inComponent: Int)
      

      当用户选择组件中的一行时,由选取器视图调用。

      这允许例如在选择更改时更新文本字段,只需松开手指。

      【讨论】:

        【解决方案3】:

        Swift 4: 实现选择器视图委托:

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

        例子:

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

        或者

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

        例子:

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

        【讨论】:

          【解决方案4】:

          最好重写这个函数

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

          UIPickerView 类中实时观察变化。

          【讨论】:

          • 不适合我。它只是在滚动停止时调用。
          【解决方案5】:

          UIPickerViewDelegatepickerView:didSelectRow:inComponent:

          【讨论】:

            【解决方案6】:

            如果您查看UIPickerViewDelegate,它有:

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

            只需设置您的选择器视图委托并实现它。

            【讨论】:

            • 是否可以在选择器视图滚动时实时更新标签?我的意思是这需要时间。但要求是让它像在 Android 中一样工作。(这是完美的)
            • 老问题,但我的建议是,不要试图强迫 iOS 成为 Android,因为任何一个平台的用户都可能习惯于不同的功能。没有“对”或“错”之分,只是不同。
            猜你喜欢
            • 2017-06-12
            • 2016-10-17
            • 2015-08-08
            • 2017-02-27
            • 1970-01-01
            • 2013-07-06
            • 2018-08-30
            • 2012-06-28
            • 1970-01-01
            相关资源
            最近更新 更多