[英]UIPickerView depending on first Component does not update UI
I want to build a UIPicker with nested data and 2 Components.我想用嵌套数据和 2 个组件构建一个 UIPicker。 The 2nd Component should be dependent on the selection of the 1st Component (eg when selected fruits -> display banana, apple...; when selected vegetables -> display tomatoes...).
The 2nd Component should be dependent on the selection of the 1st Component (eg when selected fruits -> display banana, apple...; when selected vegetables -> display tomatoes...).
This works, but the UI of the 2nd Component is not updated directly.这有效,但不会直接更新第二个组件的 UI。 I have to tap the 2nd Component to see the Titles.
我必须点击第二个组件才能看到标题。 I tried to update the Component (
picker.reloadComponent(1)
)and also AllComponents picker.reloadAllComponents()
after Selection.我尝试在选择后更新组件(
picker.reloadComponent(1)
)和 AllComponents picker.reloadAllComponents()
。
Any ideas?有任何想法吗?
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var picker: UIPickerView!
var plants = [Dictionary<String, Any>]()
var groups:[String] = [String]()
override func viewDidLoad() {
super.viewDidLoad()
plants.append([
"name": "Fruits",
"groups": [
"Banana",
"Apple"
]
])
plants.append([
"name": "Veggies",
"groups": [
"Tomatoe",
"Salad",
"Cucumber"
]
])
if plants[0]["groups"] != nil {
groups = plants[0]["groups"] as! Array
}
picker.delegate = self
picker.dataSource = self
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return plants.count
} else if component == 1 {
return groups.count
}
return 0
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if component == 0 {
// Update groups array, based on selection
if plants[row]["groups"] != nil {
groups = plants[row]["groups"] as! Array
}
picker.reloadComponent(1) //also tried picker.reloadAllComponents() here
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
if plants[row]["name"] != nil {
return plants[row]["name"] as! String
}
} else if component == 1 {
// return values of current group
return groups[row]
}
return ""
}
}
Thanks in advance!提前致谢!
Swift 4.2 / xCode 10斯威夫特 4.2/xCode 10
Your code works fine.你的代码工作正常。 If your problem is that you want the second component be reloaded to its first item, try this after
picker.reloadComponent(1)
:如果您的问题是您希望将第二个组件重新加载到它的第一个项目,请在
picker.reloadComponent(1)
之后尝试此picker.reloadComponent(1)
:
picker.selectRow(0, inComponent: 1, animated: true)
Otherwise please be more specific about the problem.否则,请更具体地说明问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.