UIPickerView 사용하기
간단한 UIPickerView를 만들어 봤습니다.
UIPickerViewDataSource를 통해 PickerView의 데이터를 세팅하고
UIPickerViewDelegate를 통해 PickerView의 이벤트를 처리할 수 있습니다.
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) 에서 선택한 row의 값을 알 수 있습니다.
아래 이미지와 소스코드를 비교해보시면 좀 더 이해하기 편합니다.
궁금하신점은 댓글로 달아주세요.
해피코딩 :)
Preview
Source
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// PickerViewViewController.swift | |
// UIKit component handling | |
// | |
// Created by Taehyeon Han on 2018. 8. 3.. | |
// Copyright © 2018년 calmone. All rights reserved. | |
// | |
import UIKit | |
class PickerViewViewController: BaseViewController, UIPickerViewDelegate, UIPickerViewDataSource { | |
lazy var pickerView: UIPickerView = { | |
// Generate UIPickerView. | |
let picker = UIPickerView() | |
// Specify the size. | |
picker.frame = CGRect(x: 0, y: 150, width: self.view.bounds.width, height: 180.0) | |
// Set the backgroundColor. | |
picker.backgroundColor = .white | |
// Set the delegate. | |
picker.delegate = self | |
// Set the dataSource. | |
picker.dataSource = self | |
return picker | |
}() | |
private let values: [String] = ["A","B","C","D","E","F","G","H","I"] | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view. | |
// Add UIPickerView on view | |
self.view.addSubview(self.pickerView) | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
func numberOfComponents(in pickerView: UIPickerView) -> Int { | |
return 1 | |
} | |
// Data source method that returns the number of rows to display in the picker. | |
// (Implementation required) | |
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { | |
return values.count | |
} | |
// Delegate method that returns the value to be displayed in the picker. | |
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { | |
return values[row] | |
} | |
// A method called when the picker is selected. | |
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { | |
print("row: \(row)") | |
print("value: \(values[row])") | |
} | |
} |
Github
https://github.com/calmone/iOS-UIKit-component
Reference