今天我們要介紹UIPickerView,UIPickerView可以讓你在列表中選擇所需要的項目,後面有一個練習會用到UIPickerView,就讓我們期待一下吧~現在先來簡單介紹如何使用UIPickerView!
首先我們在storyboard裡面新增UIPickerView以及等等用來顯示UIPickerView值的UILabel
接著宣告一筆資料用於在UIPickerView上顯示
let week = ["星期一","星期二","星期三","星期四","星期五","星期六","星期日"]
也要記得設定UIPickerView的delegate和dataSource
接著寫一個extension
extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource {
// UIPickerView 有幾列可以選擇
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
// UIPickerView 各列有多少行資料
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return week.count
}
// UIPickerView 每個選項顯示的資料
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return week[row]
}
// UIPickerView 改變選擇後執行的動作
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
lbl.text = week[row]
}
}
如此一來就完成了一個簡單的UIPickerView囉
執行結果如下