Michael Reilly
Michael Reilly

Reputation: 120

pickerView unexpectedly found nil while unwrapping an Optional

I have the following code. Get no errors. App crashes. Not sure if I initialized correctly. Please, any help is much appreciated.

@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]
}

Reached a mental block. Need someone to jar my noggin. Appreciated.

Upvotes: 1

Views: 1614

Answers (1)

Bug Hunter Zoro
Bug Hunter Zoro

Reputation: 1915

If i understood your question correct, it seems that you have the picker settings done in your storyboard OR XIB but the picker does not seem to populate the data from pickerData array.

I tried your code and its working very well it may be the linking of IBOutlet which you might have not done to the correct view controller class, Also if you are using the storyboard/XIB approach please try adding the datasource and delegate from the .storyboard or .xib file itself

enter image description here

OR

due to some funny reason the pickerData might be getting flushed out you may check that using the debugger.

If all the settings are done correct and then too you are not able to see the final output then sometimes when you create a new cocoa touch class files they are not created correct so you delete them and recreate them again (I know real stupid but it really works sometimes)

Upvotes: 2

Related Questions