我是Swift和Xcode的新手,我想为在SegmentedControl中选择Segment的关系将行设置为PickerView。我尝试了以下操作,将数组firstInputUnitChooseData
设置为PickerView firstInputUnitChoose
的行:
class FirstViewController: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var wantedInputProperty: UISegmentedControl!
@IBOutlet weak var firstInputUnitChoose: UIPickerView!
var wantedInputPropertyData: [String] = [String]()
var firstInputUnitChooseData: [String] = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Connect data
self.firstInputUnitChoose.delegate = self
self.firstInputUnitChoose.dataSource = self
wantedInputProperty.addTarget(self, action: #selector(FirstViewController.doSomething), for: .valueChanged)
}
@IBAction func doSomething() {
let choosableFirstUnit = wantedInputProperty.titleForSegment(at: wantedInputProperty.selectedSegmentIndex)
switch choosableFirstUnit {
case "p", "p,h", "p,s", "p,t", "p,x", "p,\u{03C1}":
firstInputUnitChooseData = ["Bar", "MPa", "Pa"]
case "t", "t,x" :
firstInputUnitChooseData = ["°C", "K"]
case "h,s", "h,\u{03C1}":
firstInputUnitChooseData = ["J/Kg", "kJ/Kg"]
default:
firstInputUnitChooseData = ["X"]
}
}
// The number of columns of data
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
// Number of rows of data
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return firstInputUnitChooseData.count
}
// The data to return for the row and component (column) that's being passed in
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return firstInputUnitChooseData[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// Create action for selected PickerView row
}
如果我在print(chooseableFirstUnit)
中使用print(firstInputUnitChooseData)
或func DoSomething()
,它将在控制台中输出正确的数据。
例如:如果设置了数组
firstInputUnitChooseData = [“ Bar”,“ MPa”,“ Pa”]
直接在func viewDidLoad()
内部,它可以工作,但这不是我想要的。
答案 0 :(得分:1)
您需要重新加载pickerView,因此在函数doSomething
的末尾要做
self.firstInputUnitChoose.reloadAllComponents()