比起直接在畫面中放許多選取器,從畫面中彈出的選取器可能更實用一點,主要原因就是選取器太佔螢幕的空間了,如果畫面中存在不只一個 Text Field,每個 Text Field 能分別彈出不同的選取器,而不是一個 Text Field 就放一個 Picker View 到畫面,相信這樣使用者體驗會好很多,今天就試著做會彈出的選取器出來!
能完成它的方法我查到不只兩三種,甚至有使用 Objective-C 來寫的,這裡會使用最簡單的方法!
放入兩個 Text Field。
兩個陣列分別存兩個 Picker View 的資料。
let location = ["台北","新北","桃園","台中","台南","高雄"]
let temperature = ["30°C","31°C","32°C","33°C","34°C"]
@IBOutlet weak var locationTextField: UITextField!
@IBOutlet weak var temperatureTextField: UITextField!
var locationPickerView = UIPickerView()
var temperaturePickerView = UIPickerView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
locationPickerView.dataSource = self
locationPickerView.delegate = self
temperaturePickerView.dataSource = self
temperaturePickerView.delegate = self
locationTextField.inputView = locationPickerView
temperatureTextField.inputView = temperaturePickerView
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
extension ViewController: UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == locationPickerView {
return location.count
}
if pickerView == temperaturePickerView {
return temperature.count
}
return 0
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == locationPickerView {
return location[row]
}
if pickerView == temperaturePickerView {
return temperature[row]
}
return nil
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == locationPickerView {
locationTextField.text = location[row]
}
if pickerView == temperaturePickerView {
temperatureTextField.text = temperature[row]
}
}
}
選取器的使用就介紹到這裡,感謝收看。