Tim Chamberlin Tim Chamberlin - 5 months ago 17
Swift Question

swift - check if uitextfield in another class is empty

I want to validate a form that is in a container in a parent view controller. How can I validate the form (check that all fields are not

) when a button in the parent view controller is clicked. The button has an
in the parent view controller that calls a method from the form's class.

@IBAction func submitOrder(sender: AnyObject) {
let formView = FormViewController()

The method is,

func getFieldValues() {
if (self.nameField.text == "") {
print("Name field is empty")

in the child view has the IBOutlet,

@IBOutlet weak var nameField: UITextField!

When the button in the parent view controller is clicked I get the classic error,

fatal error: unexpectedly found nil while unwrapping an Optional value

So this has something to do with optionals or the parent view controller not recognizing the text fields in the container view.


Lou is correct about the root of the problem being the new, unconnected instance of FormViewController. To get the parent view controller to recognize the uiTextFields of the container view, you have to use prepareForSegue. After naming the containerView segue in the storyboard, you have to implement this method.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "formView" {
        formView = segue.destinationViewController as? FormViewController

formView is the empty instance of FormViewController declared within the class. Making this connection allows the parent view class to get the values of the UITextFields in for FormViewController