如何在单个页面中实现多个UIPickerView?

时间:2017-06-01 14:36:06

标签: ios swift uipickerview

我正在文本字段中实施UIPickerView,如下所示:

public func numberOfComponents(in pickerView: UIPickerView) -> Int{
    return 1
}

public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return states.count // states is an array of strings
}

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

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    textField.text = states[row]
    self.view.endEditing(false)
}

我希望有另一个实现UIPickerView的文本字段。我该怎么办?我可以更改上面实现的方法以包含两个文本字段吗?

1 个答案:

答案 0 :(得分:5)

您可以轻松地将每个picker设置为标记值,​​例如:

let firstPV = UIPickerView()
pickerV.tag = 1

let secondPV = UIPickerView()
secondPV.tag = 2

通过这种方式,您只需要评估PickerView协议中的tag属性,例如:

func numberOfComponents(in pickerView: UIPickerView) -> Int {

    switch pickerView.tag {
        case 1:
            return 1
        case 2:
            return 3
    default:
        return 0
    }
}