我的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
中的另一个字符串显示。
答案 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]
}
}