昨天我們已經能把單一地點的天氣資訊顯示到手機App上面了,接著我們會利用UIButton讓我們可以選擇想要的地點及時段!
首先,我們先拉一個UIButton進storyboard裡並拉好@IBOutlet
接著我們要寫按下Button後的@IBAction,我們會利用UIPickerView來完成選擇地點和時間的功能!
我們先宣告常數及變數
並在ViewDidLoad裡設定UIPickerView的DataSource和Delegate
接著來寫選取地點時間UIPickerView的function
func locationView() {
let alertView = UIAlertController(
title: "選擇地點",
message: "\n\n\n\n\n\n\n\n\n",
preferredStyle: .alert
)
let cancelAction = UIAlertAction(
title: "取消",
style: .cancel,
handler: nil
)
let okAction = UIAlertAction(
title: "確認",
style: .default,
handler: {_ in
self.loadAPI(locationName: self.selectLocation, time: self.selectTime)
self.timeView()
}
)
alertView.view.addSubview(locationPickerView)
alertView.addAction(cancelAction)
alertView.addAction(okAction)
present(alertView, animated: true, completion: nil)
}
func timeView() {
let alertView = UIAlertController(
title: "選擇時間",
message: "\n\n\n\n\n\n\n\n\n",
preferredStyle: .alert
)
let cancelAction = UIAlertAction(
title: "取消",
style: .cancel,
handler: nil
)
let okAction = UIAlertAction(
title: "確認",
style: .default,
handler: {_ in self.loadAPI(locationName: self.selectLocation, time: self.selectTime)}
)
alertView.view.addSubview(timePickerView)
alertView.addAction(cancelAction)
alertView.addAction(okAction)
present(alertView, animated: true, completion: nil)
}
最後寫一個extension
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 == timePickerView {
return timeData.count
}
return 0
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == locationPickerView {
return location[row]
}
if pickerView == timePickerView {
return timeData[row]
}
return nil
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == locationPickerView {
selectLocation = location[row]
}
if pickerView == timePickerView {
selectTime = row
}
}
}
我們就能成功選擇地點和時間啦!