Collin
Collin

Reputation: 27

How do I display multiple textfields to my labels?

I'm not sure if how I worded the question makes much sense so let me summarize.

I have 2 UITexfields and 2 UILabels.

I have it all working properly in terms of when I type into my first textField and hit return it will display my text.

Now I'm not sure how to get the same to apply to my other TextField and Label. I read that if I apply a tag to my textfield in Xcode "1" that I can apply tag "2" to my other textfield.

Here is the code I am using so when I press return it'll display textfield tag "1".

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    if textField.tag == 1 {
        nameDisplay?.text = textField.text!
    }

    return true
}

So to completely round this out, I want to display both separate textfields on each separate label.

Upvotes: 0

Views: 368

Answers (1)

rmaddy
rmaddy

Reputation: 318944

Simply add an else to your if.

if textField.tag == 1 {
    nameDisplay.text = textField.text
} else {
    otherLabel.text = textField.text
}

Please note you do not need the ? or ! in that code.

Another option, if you have outlets for your text fields, is to do the following instead of bothering with tags:

if textField == someTextFieldOutlet {
    nameDisplay.text = textField.text
} else {
    otherLabel.text = textField.text
}

where someTextFieldOutlet is obviously needs to be the actual name of the appropriate text field outlet you have.

Upvotes: 2

Related Questions