swift3 利用UIPickerView,讓textfield 選擇更有趣

  1. 首先必須先繼承UIPickerViewDataSource,UIPickerViewDataSource
class ViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource{

2.準備前置條件產生data和PickerView

@IBOutlet weak var datePickerTxt: UITextField!
//data是PickerView的內容
var data = [“1”,”2",”3"]
//產生PickerView
var picker = UIPickerView()

3.在viewDidLoad設定代理人和資料來源為viewController,讓textfiled的輸入方式改為PickerView和加上手勢按鈕

override func viewDidLoad() {
super.viewDidLoad()
//設定代理人和資料來源為viewController
picker.delegate = self
picker.dataSource = self
//讓textfiled的輸入方式改為PickerView
datePickerTxt.inputView = picker
//加上手勢按鈕
let tap = UITapGestureRecognizer(target: self, action: #selector(closeKeyboard))
view.addGestureRecognizer(tap)
}

4.這是當手勢控制觸發時,關閉編輯畫面

func closeKeyboard(){
self.view.endEditing(true)
}

5.繼承UIPickerViewDataSource一定要實作的方法為numberOfComponents和numberOfRowsInComponent。另繼承UIPickerViewDelegate選擇性實作的方法為titleForRow和didSelectRow方法

//有幾個區塊
public func numberOfComponents(in pickerView: UIPickerView) -> Int{
return 1
}
//裡面有幾列
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
return data.count
}
//選擇到的那列要做的事
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
datePickerTxt.text = data[row]
}
//設定每列PickerView要顯示的內容
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return data[row]
}
}

Originally published at swifthao的ios學習紀錄blog.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.