正文:
以一個簡單的例子來應用 UIPickerView
成果圖:
程式碼:
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var varLabel: UILabel!
@IBOutlet weak var customPickerView: UIPickerView!
let numbers = ["0","1","2","3","4","5"]
var whatNumber = "0"
override func viewDidLoad() {
super.viewDidLoad()
customPickerView.delegate = self
customPickerView.dataSource = self
}
// MARK: - UIPickerViewDataSource 必須實作的方法:
// UIPickerView 有幾列可以選擇
func numberOfComponents(
in pickerView: UIPickerView) -> Int {
return 1
}
// UIPickerView 各列有多少行資料
func pickerView(_ pickerView: UIPickerView,
numberOfRowsInComponent component: Int) -> Int {
return numbers.count
}
// MARK: -
// UIPickerView 每個選項顯示的資料
func pickerView(_ pickerView: UIPickerView,
titleForRow row: Int, forComponent component: Int)
-> String? {
return numbers[row]
}
// UIPickerView 改變選擇後執行的動作
func pickerView(_ pickerView: UIPickerView,
didSelectRow row: Int, inComponent component: Int) {
whatNumber = numbers[row]
// 將改變的結果印出來
print("選擇的是 \(whatNumber)")
varLabel.text = "\(whatNumber)"
}
}