pickerView 在展开 Optional 时意外发现 nil

pickerView unexpectedly found nil while unwrapping an Optional

我有以下代码。没有错误。应用程序崩溃。不确定我是否正确初始化。非常感谢任何帮助。

@IBOutlet weak var myCostPicker: UIPickerView!

var costCode = String()

override func viewDidLoad() {
    super.viewDidLoad()
    if let projectNum = projectNum {
        projectNumTitle.title = projectNum

    }

    updateLabels()
    myCostPicker.dataSource = self
    myCostPicker.delegate = self
    myCostPicker.showsSelectionIndicator = true
    self.view.backgroundColor = UIColor.blackColor()
}

let pickerData = ["Nothing", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q"]

let costCodeData = ["Nothing", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q"]

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

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

// MARK: - Picker Delegates
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String {
    return pickerData[row]
}

func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    let titleData = pickerData[row]
    var myTitle = NSAttributedString(string: titleData, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 15.0)!,NSForegroundColorAttributeName:UIColor.whiteColor()])
    return myTitle
}

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    myLabel.text = pickerData[row]
    costCode = costCodeData[row]
}

达到精神障碍。需要有人来刺激我的头脑。赞赏。

如果我理解你的问题是正确的,那么你似乎已经在故事板或 XIB 中完成了选择器设置,但选择器似乎没有填充来自 pickerData 数组的数据。

我试过你的代码,它工作得很好,它可能是 IBOutlet 的链接,你可能没有链接到正确的视图控制器 class,另外如果你使用 storyboard/XIB 方法请尝试从 .storyboard 或 .xib 文件本身添加数据源和委托

由于一些有趣的原因,pickerData 可能会被清除,您可以使用调试器检查一下。

如果所有设置都正确完成,然后您也看不到最终输出,那么有时当您创建新的 cocoa touch class 文件时,它们创建不正确,因此您删除它们并重新创建它们(我知道这很愚蠢,但有时确实有效)