在我的應用我有一個文本字段(距離)2個不同的陣列上,分段控制,選擇單位參考(公里/英里):PickerView - 如何返回基於分段控制選擇
我有另一個顯示UIPickerView的文本字段(速度)。這個選擇器視圖可以根據用戶選擇的單位填充2個數組。除此之外,所有工作都是有效的,即使未顯示選取器視圖並更改選定內容,僅當我開始滾動選取器視圖時,數組纔會更改。所以最初它顯示的是以km爲單位的陣列,即使我選擇了Mi,然後當我開始移動選取器時它會改變。
最初予置的單元基準和一個可變的2個陣列
var unitReference = "Km" // this is the initial selection on the segmented control
let paceKmArray = [" ", "Relaxing(less than 15km/h)", "Easy(15km/h-20km/h)","Medium(20km/h-25km/h)","Nice(25km/h-30km/h)","Fast(30km/h-35km/h)", "Very Fast(>35km/h)"]
let paceMiArray = [" ", "Relaxing(less than 10 mi/h)", "Easy(10mi/h-13mi/h)","Medium(13mi/h-16mi/h))","Nice(16mi/h-19mi/h))","Fast(19mi/h-12mi/h))", "Very Fast(>22mi/h)"]
然後在viewDidLoad
unitReferenceSegmentedControl.addTarget(self, action: "unitChanged:", forControlEvents: .ValueChanged);
其中調用此方法來改變所述單元的參考
func unitChanged(sender:UISegmentedControl){
if sender.selectedSegmentIndex == 0{
unitReference = "Km"
print(unitReference)
}
if sender.selectedSegmentIndex == 1{
unitReference = "Mi"
print(unitReference)
}
}
和選取器查看方法
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView.tag == 0{
return rideTypeArray[row]
}
if pickerView.tag == 1{
if unitReference == "Km"{
return paceKmArray[row]
}
if unitReference == "Mi"{
return paceMiArray[row]
}
}
return ""
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
if pickerView.tag == 0{
return rideTypeArray.count
}
if pickerView.tag == 1{
if self.unitReference == "Km"{
return paceKmArray.count
}
if self.unitReference == "Mi"{
return paceMiArray.count
}
}
return 0
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
if pickerView.tag == 0{
rideTypeTextField.text = rideTypeArray[rideTypePickerView!.selectedRowInComponent(0)] as String
}
if pickerView.tag == 1{
if unitReference == "Km"{
paceTextField.text = paceKmArray[pacePickerView!.selectedRowInComponent(0)] as String
}
if unitReference == "Mi"{
paceTextField.text = paceMiArray[pacePickerView!.selectedRowInComponent(0)] as String
}
}
}
我不確定這是做到這一點的最好方法。如果有更優雅的方式來做到這一點,我將非常樂意學習它。
如果我必須這樣做,我會採取第三個數組並將其視爲單個數據源,同時在選擇分段時在「paceKmArray」和「paceMiArray」之間切換。 – Gandalf
@Gandalf謝謝,我也試圖這樣做,但行爲並沒有改變 – mat
當您更改段選擇時,您不在選擇器上調用reloadAllComponents。作爲最後一行從'unitChanged:'調用它。當然是 – Gandalf