Swift 3 viewDidLoad() - 致命错误:在展开Optional值时意外发现nil

时间:2016-09-28 02:05:28

标签: ios swift xcode8

我已经尝试过所有以前的建议来解决这个问题,但仍然没有运气。它工作正常(UIPickerView正确填充),但现在应用程序在viewDidLoad()运行后崩溃。已验证所有IBOutlets已正确连接。试图重新创建可可触摸文件。

这是我的视图控制器代码。它必须是我忽略的小事。帮助!

class SettingsVC: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

@IBOutlet weak var targetCadenceLabel: UILabel?
@IBOutlet weak var cadenceStepper: UIStepper?
@IBOutlet weak var goalPicker: UIPickerView?

var pickerDataSource = ["improve SPM", "maintain SPM"]

override func viewDidLoad() {
    super.viewDidLoad()
    self.goalPicker?.dataSource = self
    self.goalPicker?.delegate = self


    //MARK:  Setup Tab Bar
    let tabBarItem = self.tabBarItem
    let incomingSelectedImage: UIImage! = UIImage(named: "settings_icon")?.withRenderingMode(.alwaysOriginal)
    tabBarItem?.selectedImage = incomingSelectedImage
    tabBarItem?.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor(red: 60/255, green: 159/255, blue: 255/255, alpha: 1.0)], for: UIControlState.selected)
}


//MARK: - Delegates and data sources
//MARK: Data Sources
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

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

//MARK: Delegates
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    let titleData = pickerDataSource[row]
    let myFont = UIFont.systemFont(ofSize: 18)
    let fontColor = UIColor(red: 60/255, green: 159/255, blue: 255/255, alpha: 1.0)
    let myTitle = NSAttributedString(string: titleData, attributes: [NSFontAttributeName: myFont,NSForegroundColorAttributeName:fontColor])
    return myTitle
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

}

@IBAction func cadenceStepper(_ sender: UIStepper) {
    targetCadenceLabel?.text = Int(sender.value).description
}

@IBAction func goPremiumTapped(_ sender: UIButton) {
    print("Go Premium Button Tapped")
}    
}

1 个答案:

答案 0 :(得分:1)

您只在viewDidLoad中的一行中展开,就在这里:

let incomingSelectedImage: UIImage! = UIImage(named: "settings_icon")?.withRenderingMode(.alwaysOriginal)

在使用异常断点验证这是代码崩溃的行之后,您可能想要执行

 let incomingSelectedImage:UIImage? ..........................