George
George

Reputation: 522

How do I access text in UITextField from another ViewController (Swift)?

I have a UITextField on one ViewController and I want to be able to have a Label on the second ViewController = whatever the user enters.

However, I get an error when trying to do this. I know Swift doesn't use import so I'm not sure what to do.

// First View Controller

 @IBOutlet weak var textOne: UITextField!

// Second View Controller

    @IBOutlet weak var theResult: UILabel!

theResult.text = textOne.text

Error: Unresolved Identifier

Upvotes: 2

Views: 4546

Answers (2)

Christian
Christian

Reputation: 22343

It looks like that you in reality want to just access the text from the UITextField and not the field itself. So you should send the text to the second ViewController from your first one by using prepareForSegue.

But before, you have to set the name of your segue so that Swift knows which data to send:

enter image description here

As you see, we name the segue segueTest.

So now we can implement the prepareForSegue-method in the FirstViewController and set the data which should be sent to the second.

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if (segue.identifier == "segueTest") {
        var svc = segue!.destinationViewController as secondViewController;

        svc.theText = yourTextField.text

    }
}

That you can do that, you have to set a variable in your SecondViewController of course:

var theText:String!

Upvotes: 4

Dennis Weidmann
Dennis Weidmann

Reputation: 1967

You need to pass a reference to your FirstViewController instance to the SecondViewController instance at prepearForSegue...

Then do something like this

//FirstViewController
@IBOutlet weak var textOne: UITextField!

func getTextOne () -> String? {
     return textOne.text
}

//SecondViewController
@IBOutlet weak var theResult: UILabel!
var firstViewControllerInstance: FirstViewController?

func showResult () {
     theResult.text = firstViewControllerInstance?.getTextOne()
}

And you are done

Upvotes: 3

Related Questions