0

I followed a Youtube tutorial to create a picker view in Swift as follows but it has a bug as described in the title on the line:

activityLevelField.inputView = activityPicker

Code:

import UIKit

class ViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource,UITextFieldDelegate {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

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

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

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        selectedActivity = activityTypes[row]
        activityLevelField.text = selectedActivity
    }

    var selectedActivity: String?
    var activityTypes = ["Less active", "active", "very active"]

    func createActivityPicker(){
        let activityPicker = UIPickerView()

        activityPicker.delegate = self
        activityPicker.dataSource = self

        activityLevelField.inputView = activityPicker
    }

    @IBOutlet weak var activityLevelField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        createActivityPicker()
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • The most likely reason is that your `activityLevelField` variable is not connected to an actual `UITextField`. Check the connection in your storyboard (I'm assuming your view controller is being loaded from a storyboard...if not, let us know). – Phillip Mills Jan 13 '19 at 01:11
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – rmaddy Jan 13 '19 at 02:51
  • activityLevelField did connect to the UITextfield. This is not the problem – Bingjie Zhou Jan 14 '19 at 21:39

1 Answers1

0

Your connection from Storyboard is broken. Check your connection from textfiled's connection inspector.

Ankur Lahiry
  • 2,253
  • 1
  • 15
  • 25