Picker View
PikcerView๋ ์ฌ๋กฏ๋จธ์ ํํ์ด๋ฉฐ Wheel์ ๋๋ ค์ ๋ฐ์ดํฐ๋ฅผ ์ ํํ ์ ์๋ ๊ธฐ๋ฅ์ ์ ๊ณตํ๋ค.
Date picker ์ Picker view๋ ๋น์ทํ ํํ์ ๊ธฐ๋ฅ์ ๊ฐ์ง๋ง ๊ตฌํํ ๋๋ ํฐ ์ฐจ์ด์ ์ด ์๋ค. Date picker๋ ํํ๋ง ์ก์์ฃผ๋ฉด ์์์ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ค์ง๋ง, picker view๋ ๊ฐ๋ฐ์๊ฐ ์ง์ ๋๋ถ๋ถ์ ๊ตฌํํด์ผํ๋ค.
pickerView๋ Delegate, Datasource๋ฅผ ์ง์ ํด์ฃผ์ด์ผํ๋ค.
Datasource
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return (<Int>)
} // ๋ํ๋ผ ๋๋ฆผํ์ ๊ฐ์(components)๋ฆฌํด
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return (<Int>)
} // ๋๋ฆผํ ์์ ์์ ๊ฐ์ (row)
Delegate
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return (<String?>)
} // ๊ฐ row์ ๋ค์ด๊ฐ title์ stringํํ๋ก ๋ฆฌํดํ๋ค.
๋ํ ํญ๋ชฉ(row)๊ฐ ์ ํ ๋ ๋๋ง๋ค ํจ์๋ฅผ ํธ์ถํด์ฃผ๋ ๋ฉ์๋๋์๋ค.
func pikcerView(_ pickerView : UIPickerView, didSelectRow row: Int, inComponent component:Int){
// ํ์ฌ ์ ํ๋ ์ธ๋ฑ์ค๊ฐ row์ ๋ค์ด์จ๋ค.
print(dataList[row]) // ํ์ฌ ์ ํ๋ ํญ๋ชฉ ์ถ๋ ฅํ๊ธฐ
}
์ ํ๋ ํญ๋ชฉ (selectedRow)
selectedRow(imComponent: Int)
๋ฉ์๋๋ฅผ ํตํด ํ์ฌ ์ ํ๋ row๋ฅผ ์ ์์๋ค.
@IBOutlet weak var pickerView: UIPickerView!
let pickedRow = pickerView.selectedRow(inComponent: 0)
pickedRow์ ์ ํ๋ row๊ฐ ๋ค์ด๊ฐ๋ค.
(๋ง์ฝ ์ ํ๋์ง ์์๋ค๋ฉด -1์ด ๋ฆฌํด๋๋ค.)
import UIKit
class ViewController: UIViewController {
let dataList = ["1","2","3","4","5"]
@IBOutlet weak var pickerView: UIPickerView!
@IBAction func picked(_ sender: Any) {
let pickedRow = pickerView.selectedRow(inComponent: 0)
print("์ ํ๋ row : ",pickedRow)
}
override func viewDidLoad() {
super.viewDidLoad()
pickerView.delegate = self
pickerView.dataSource = self
}
}
extension ViewController : UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return dataList.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return dataList[row]
}
}