Saturday, January 17, 2015

UIPickerView - One selection among multiple options


1. Drag a UIPickerView to the storyboard

2. Control-Drag the UIPickerView to the ViewController for datasource and delegate

3. Complete the code as below:

import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

    let languageList = ["United States", "United Kingdom", "Australia", "China", "Hong Kong", "Taiwan"]
    let languageCodeList = ["en-us", "en-gb", "en-au", "zh-cn", "zh-hk", "zh-tw"]
    
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return languageList.count
    }
    
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        return languageList[row]
    }
    
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        println("language code is \(languageCodeList[row])")

    }

No comments:

Post a Comment