Search code examples
iosswiftuitextfieldiboutlet

Cannot link an IBOutlet for UITextField


I tried adding my an outlet on my Main.Storyboard and CTRL + dragged it into my corresponding view controller.

class LoginViewController: UIViewController {
    @IBOutlet weak var nameField: UITextField!
}

Upon doing this, I am getting this error

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIViewController 0x7f7ff051e860> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key nameField.'

What could be causing this issue?


Solution

  • The problem here is that it's creating an instance of UIViewController, not an instance of LoginViewController. You can tell because the error message says <UIViewController 0x7f7ff051e860>, not <LoginViewController 0x7f7ff051e860>. Since UIViewController doesn't have a nameField outlet, you get an error when the storyboard loader tries to connect that outlet.

    There are two likely explanations:

    1. The custom class in the storyboard isn't set to LoginViewController. Select the view controller in the scene in your storyboard. From the menu bar, choose View > Utilities > Show Identity Inspector. Then, in the Identity Inspector (right-hand pane), make sure the class is set to LoginViewController.

      setting the custom class

      You must have set the custom class at some point, if Xcode let you connect the outlet. But you might have accidentally undone the change afterward.

    2. The file containing the LoginViewController source code isn't part of your target (your app). In this case, there should be another message earlier in your debug console, like this:

      2016-02-08 22:08:04.569 test[3049:9594499] Unknown class _TtC4test16MyViewController in Interface Builder file.
      

      To fix this, open your LoginViewController.swift file (or whatever file contains that class). From the menu bar, choose View > Utilities > Show File Inspector. In the File Inspector (right-hand pane), find the Target Membership section and turn on the checkbox next to your app.

      adding to the target