同一个UIViewcontroller中的两个拣货员

时间:2016-10-08 23:54:22

标签: swift xcode swift2 uipickerview

我正在创建一个应用程序,用户可以选择在同一个视图控制器中使用两个UIPickers。如何才能做到这一点。我想要一个选择器显示海滩名称,另一个选择显示生活在海滩上的动物。

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

以下是执行此操作的快速指南:

1.在课堂上初始化拣货员和拣货员数据集:

 var pickerView1 = UIPickerView()
 var pickerView2 = UIPickerView()

 var pickerView1Data: [String] = ["Waikiki", "Long Beach", ...]
 var pickerView2Data: [String] = ["Crab", "Seal", ...]

2.设置委托,数据源和标签(在viewDidLoad中)。

 pickerView1.dataSource = self
 pickerView1.delegate = self
 pickerView1.tag = 1

 pickerView2.dataSource = self
 pickerView2.delegate = self
 pickerView2.tag = 2

3.设置行数

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

    var returnIndex: Int = 0

    if pickerView.tag == 1 {
        returnIndex = pickerView1Data.count
    } else if pickerView.tag == 2 {
        returnIndex = pickerView2Data.count
    }

    return returnIndex
}

4.返回每行的数据

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

    var returnRow: String!

    if pickerView.tag == 1 {
        returnRow = pickerView1Data[row]
    } else if pickerView.tag == 2 {
        returnRow = pickerView2Data[row]
    }

    return returnRow
}

5.Capture pickerView选择

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    // This method is triggered whenever the user makes a change to the picker selection.

    if pickerView.tag == 1 {

        beachTextField.text = pickerView1Data[row]

    } else if pickerView.tag == 2 {

        animalTextField.text = pickerView2Data[row]

    }

}

当然,这是设置选择器视图所需要做的所有其他事情,但这应该是两个选择器视图需要处理的所有内容。