[swift] 簡易建立UIPickerView(1)

Jacob 黃炬楷
Jul 30, 2017 · 4 min read

在 ViewController的 Class 繼承 UIPickerViewDelegate及UIPickerViewDataSource

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

這裡繼承的UIPickerViewDelegate功能是,管理使用者對PickerView的動作及行為。而UIPickerDataSource的功能是,管理PickerView中每一個選項的內容。

接著在viewDidLoad的方法中,把dataSource和delegate的權限,交給self (ViewController)。

override func viewDidLoad() {super.viewDidLoad()pickerView.dataSource = selfpickerView.delegate = self}

此時,按住command鍵,點選被繼承的UIPickerViewDataSource,來看DataSource的應用方法,並找到…

public func numberOfComponents(in pickerView: UIPickerView) -> Int

以上這個方法是指,有多少個行(column)

public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int

及以上這個方法是指,有多少個列(row)

行與列 傻傻分不清楚

把上面兩個方法做複製,並貼到ViewController裡面,可以先做簡單的測試,例如 2行及 10列,如下:

func numberOfComponents(in pickerView: UIPickerView) -> Int{return 2}func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{return 10}

測試完行與列的顯示後,就可以開始建立內容的文字

先在全域範圍中,建立一個空的pickerViewInfo陣列

var pickerViewInfo = [String]()

並在ViewDidLoad方法中,建立一個for迴圈,來設定列的數量,並利用append把載入迴圈的物件,放入pickViewInfo的陣列

for n in 1...5{let info = "number\(n)"pickerViewInfo.append(info)}

在UIPickerViewDelegate的方法中,找到 titleForRow的方法,來設定顯示的文字

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{return pickerViewInfo[row]}

part 2 部分會介紹到該怎麼在不同的”行“顯示不同的文字內容

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade