如何在iOS中连接选择视图和标签?

时间:2018-01-13 15:31:45

标签: ios arrays swift uipickerview

我的pickerView上有两个Label和两个ViewController

问题是如何将label连接到pickerView的数据数组(字符串类型)并显示在label选择的pickerView单元格中?

@IBOutlet weak var valuetype1: UILabel!

    var pickerData: [String] = [String]()


 override func viewDidLoad() {
        super.viewDidLoad()

        self.picker1.delegate = self
        self.picker1.dataSource = self
        self.picker2.delegate = self
        self.picker2.dataSource = self

        pickerData = ["Годы", "Месяцы", "Недели", "Дни", "Часы", "Минуты"]
}

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


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


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

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    valuetype1.text = pickerData[row]
    valuetype2.text = pickerData[row]
}

你怎么能看到我将标签(valuetype(1..2))连接到pickerData,但它总是在label的一个字符串中显示。我需要在label中选择的第一个pickerView1字符串和label中选择的第二个pickerView2中的另一个字符串显示。

1 个答案:

答案 0 :(得分:0)

UIPickerViewDelegate有一个名为pickerView(_:didSelectRow:inComponent:)的方法。将此方法添加到VC类。只要用户选择一行,就会调用此方法。

您的实施应该与此类似。

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    valuetype1.text = pickerData[row]
}

有关更多信息,请参阅apple docs:https://developer.apple.com/documentation/uikit/uipickerviewdelegate/1614371-pickerview

编辑:

当您使用相同的控制器作为多个UIPickerViews的委托时,您可以通过比较pickerView方法上的pickerView(_:didSelectRow:inComponent:)参数来检查哪个选择器视图触发了方法调用。

试试这个:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if pickerView == picker1 {
        valuetype1.text = pickerData[row]
    } else if pickerView == picker2 {
        valuetype2.text = pickerData[row]
    }
}