iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 18
0

比起直接在畫面中放許多選取器,從畫面中彈出的選取器可能更實用一點,主要原因就是選取器太佔螢幕的空間了,如果畫面中存在不只一個 Text Field,每個 Text Field 能分別彈出不同的選取器,而不是一個 Text Field 就放一個 Picker View 到畫面,相信這樣使用者體驗會好很多,今天就試著做會彈出的選取器出來!

能完成它的方法我查到不只兩三種,甚至有使用 Objective-C 來寫的,這裡會使用最簡單的方法!

  • 放入兩個 Text Field。
    https://ithelp.ithome.com.tw/upload/images/20201001/20129680xBQBtZd6pp.png

  • 兩個陣列分別存兩個 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()
  • 讓 Text Field 的輸入方式改為 Picker View。
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)
}
  • 最後是兩個 Picker View 的三階段對話函數,以及選擇後填入對應 Text Field。
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]
        }
        
    }
    
}

選取器的使用就介紹到這裡,感謝收看。


上一篇
《DAY 17》選取器
下一篇
《DAY 19》生命週期
系列文
《菜鳥のSwift》持續30天開發挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言