致命错误:在解开UIPickerView的Optional值时意外发现nil

时间:2016-07-30 15:57:31

标签: ios swift uipickerview

我是Swift的初学者,我在网上找到了这个代码。我试过询问作者,但是他们不会回答,因为我刚刚开始,如果有人能够确定错误的确切原因以及我如何解决这个问题,我将非常感激。我继续得到错误“致命错误:在解开一个Optional值时意外地发现了nil”。我尝试在线寻找解决方案,但它没有用。有人可以帮助我吗?非常感谢! (一点解释会很棒!:))

这是我的(他们的)代码:

import UIKit

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate

{
    @IBOutlet weak var pickerView: UIPickerView!


    var pickerDataSource = ["White", "Red", "Green", "Blue"];


    override func viewDidLoad() {

        super.viewDidLoad()
        self.pickerView.dataSource = self; // This is where the error occurs
        self.pickerView.delegate = self;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


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

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

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

    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        if(row == 0)
        {
            self.view.backgroundColor = UIColor.whiteColor();
        }
        else if(row == 1)
        {
            self.view.backgroundColor = UIColor.redColor();
        }
        else if(row == 2)
        {
            self.view.backgroundColor =  UIColor.greenColor();
        }
        else
        {
            self.view.backgroundColor = UIColor.blueColor();
        }
    }

1 个答案:

答案 0 :(得分:1)

将故事板中的UIPickeView插座连接到viewcontroller 示例:这种方式Ctrl + Drag  我认为现在应该可行了。 如果不是问题,请在下面发表评论。