如何设置Arry具有4个组件的pickerView?迅速

问题描述

我尝试了很多,但这只是显示“?”在四个组成部分的行中。 是否可以将String像4个组件的标题一样放在Array Like的第一位?我本来想将数组中所有的Integer都更改为Strings,但这会花费我太多时间...

let componentOne = [1...1000]
    let componentTwo = [1...59]
    let componentThree = [1...59]
    let componentFour = [1...3]
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 4
    }
    func pickerView(_ pickerView: UIPickerView,numberOfRowsInComponent component: Int) -> Int {
        if component == 0 {
            return 1000
        }
        if component == 1 {
            return 59
        }
        if component == 2 {
            return 59
        }
        if component == 3 {
            return 3
        }
        return component
    }
        
    func pickerView(_ pickerView: UIPickerView,titleForRow row: Int,forComponent component: Int) -> Int {
        if component == 0 {
            let row = componentOne[row]
            return 1000
            }
            if component == 1 {
                let row = componentTwo[row]
                return 59
                }
                if component == 2 {
                    let row = componentThree[row]
                    return 59
                    }
                    if component == 3 {
                        let row = componentFour[row]
                        return 10
                        }
        return row
                    }
    ```

解决方法

您不能只更改委托方法。这是correct个:

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

您有:

func pickerView(_ pickerView: UIPickerView,forComponent component: Int) -> Int

无论如何,您都必须返回String? -如果将函数的返回类型更改为Int,则它不符合协议要求。

好处是,您可以轻松地从String中创建一个Int。只需像这样使用字符串插值:

/// Inside pickerView(_:titleForRow:forComponent:)

let row = componentOne[row]
    return "\(1000)"
}