์ƒˆ์†Œ์‹

๐Ÿ“ฑ iOS/-- UIKit

(iOS) UIControl - Picker View

  • -

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]
    }

}

Contents

ํฌ์ŠคํŒ… ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค

์ด ๊ธ€์ด ๋„์›€์ด ๋˜์—ˆ๋‹ค๋ฉด ๊ณต๊ฐ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.