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

笑着哭i 提交于 2019-12-10 23:31:45

问题


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


回答1:


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:

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!



回答2:


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



来源:https://stackoverflow.com/questions/32234811/how-do-i-access-text-in-uitextfield-from-another-viewcontroller-swift

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