访问存储在类Swift中的变量

时间:2015-03-05 14:51:50

标签: class swift instance uipickerview

我无法弄清楚为什么我无法访问这个变量,见下文,我想要点击运动结果的值,但sportResult.selectedSport返回nil?

let sportPickerData = SportPickerData()

    override func viewDidLoad() {
      super.viewDidLoad()

        sportPickerView.delegate = sportPickerData
        sportPickerView.dataSource = sportPickerData


class SportPickerData: NSObject, UIPickerViewDataSource, UIPickerViewDelegate {

    var sports = ["Football", "Baseball", "Hockey", "Basketball"]

    var selectedSport: String?

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

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

    func pickerView(yearPicker: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        selectedSport = sports[row]
    }

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

let sportResult = SportPickerData()


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

1 个答案:

答案 0 :(得分:0)

sportResult它不是您的选择器视图的委托或数据源,因此它的selectedSport属性永远不会被初始化,因为它的didSelectRow方法永远不会被调用。要获取selectedSport,您必须从sportPickerData获取它,这实际上是您的选择器的委托和数据源

let sportResult = SportPickerData() // delete this line 


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