使用 UiPickerView 输入数字

number input with UiPickerView

在我的用例中,我想添加由 4 位数字组成的数字,如图所示。第一位数字应为 0 或 1。

到目前为止我的代码是:

func numberOfComponents(in weightPickerView: UIPickerView) -> Int {
    return 4
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return loopingMargin * numbers.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return numbers[row % numbers.count]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    digits[component] = row % numbers.count
    let weightString = "\(digits[0])\(digits[1])\(digits[2])\(digits[3])"
    weightField.text = weightString
}

我怎样才能做到这一点?

你可以试试

 func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
     if(component == 0)
     {
        return 2
     }
     else
     {
       return loopingMargin * numbers.count
     }

 }

正在考虑:

let numbers = [2,10,10,10]
var digits = [0,0,0,0]

像这样更新您的委托方法:

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return numbers[component]
}

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

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    digits[component] = row
    let weightString = "\(digits[0])\(digits[1])\(digits[2])\(digits[3])"
    weightField.text = weightString
}