如何连接UIPickerView + Button +调用字典以在标签中显示

时间:2015-03-03 00:25:28

标签: swift

我有一个标签,一个选择器(年)和一个按钮。我希望能够在选择器上选择年份,点击按钮,然后显示与年份相关的数据(字典)。这是我目前的代码

    class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!


    @IBOutlet weak var picker: UIPickerView!


    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent      
    component: Int) -> Int {
        return years.count
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, 
    forComponent component: Int) -> String! {
        return years[row]
    }


    /*    func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, 
    inComponent component: Int) {
        label.text = "\(years[row])"
    }

    */

   @IBAction func button(sender: UIButton) {
        label.text = 
    }

这是我的模特:

 let years = ["2015", "2014", "2013", "2012"]

    let winners = [
        2015: "Patriots",
        2014: "Seahawks",
        2013: "Ravens",
        2012: "Giants"
    ]

1 个答案:

答案 0 :(得分:0)

你需要做一些事情来完成这项工作。首先,使viewController符合UIPickerViewDataSourceUIPickerViewDelegate,并在viewDidLoad中设置您的选择器的数据源和委托。然后,您将需要使用委托方法pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)来响应对pickerView的更改。将选择存储在实例变量中,你应该好好去:

class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var picker: UIPickerView!

    let years = [2015, 2014, 2013, 2012]

    let winners = [
        2015: "Patriots",
        2014: "Seahawks",
        2013: "Ravens",
        2012: "Giants"
    ]

    var selectedYear: Int?

    override func viewDidLoad() {
        super.viewDidLoad()
        picker.delegate = self
        picker.dataSource = self
    }

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return years.count
    }

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        selectedYear = years[row]
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        return "\(years[row])"
    }


    @IBAction func button(sender: UIButton) {
        if let year = selectedYear {
            if let winner = winners[year] {
                label.text = winner
            }
        }
    }
}