[swift] 簡易建立UIPickerView(2)

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

在part 1的文章中,我們建立了兩個「行」的pickerView,不過兩行的內容都一摸一樣,因此在這裡我們要各別做設定,讓兩行的顯示內容都不一樣。

建立兩個陣列,來代表兩個行的顯示內容
n1為 50~60
n2為90~100

var n1 = Array(50...60)var n2 = Array(90...100)

在「行」內,設定「列」的數量,numberOfRowsInComponent
這裡的component是 0 代表的是第一個行,component是 1就代表第二個行,以此類推,因此用if判斷,當component是 1時,就返回n1陣列的數量。

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{if component == 0 {return n1.count}else{return n2.count}}

設定「列」 所顯示的內容,titleForRow
返回與上雷同

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{if component == 0{return String(n1[row])}else{return String(n2[row])}}}
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