UIPickerView: unexpectedly found nil while unwrapping an Optional value

蹲街弑〆低调 提交于 2019-12-11 20:35:02

问题


I am trying to implement a UIPickerView to my App. Though I haven't got an error, when I run the app it crashes with following error:

unexpectedly found nil while unwrapping an Optional value

class LobbyViewController: UIViewController {


   @IBOutlet weak var textfield: UITextField!
   var picker: UIPickerView!

   var radius = [2, 5, 10, 15, 20, 25, 50, 100, 1000]


   override func viewDidLoad() {
        super.viewDidLoad()
        picker.dataSource = self
        picker.delegate = self
        self.textfield.inputView = picker
   }

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

}

extension LobbyViewController: UIPickerViewDataSource {

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

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

}

extension LobbyViewController: UIPickerViewDelegate{
    func pickerView(umkreisPicker: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String {
        return radius[row]
    }

}

Hope you can help me!


回答1:


Any hint as to which line this is happening on? My guess would be picker.dataSource = self

You do not have this set up as an outlet and it's never initialized anywhere according to what you've shared.

EDIT FOR COMMENT

So you need to initialize the picker, you can do that like you initialize most things, with it's standard init() method. Then you need to tell the text field that it's input view should be the picker.

Try adding the following to viewDidLoad()

picker = UIPickerView()
textField.inputView = picker



回答2:


You aren't ever creating your UIPickerView instance - either picker should be marked as an @IBOutlet and hooked up in your storyboard or you should create it before setting the delegate and data source.



来源:https://stackoverflow.com/questions/25314025/uipickerview-unexpectedly-found-nil-while-unwrapping-an-optional-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!