使用UiPickerView输入数字

时间:2018-03-19 15:56:06

标签: ios swift 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
}

我怎样才能做到这一点?

enter image description here

2 个答案:

答案 0 :(得分:3)

考虑到:

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
}

答案 1 :(得分:1)

你可以尝试

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

 }