Reputation: 65
Good day! So here is my issue - I need to change 2 different labels from 1 text field. Tried simple if-else logic, but it didn't work in my case.
func labelTextChanger() {
if fromUserName.text == nil {
fromUserName.text = textFileld.text
} else {
replyToUserName.text = textFileld.text
}
}
Upvotes: 0
Views: 86
Reputation: 65
So here is right code for ma case:
var zalupa = Bool()
func textFieldShouldReturn(textField: UITextField) -> Bool {
if (!zalupa) {
fromLabel.text = textField.text
zalupa = true
} else {
replyLabel.text = textField.text
zalupa = false
}
return true
}
Upvotes: 0
Reputation: 3556
You don't need the else
if you want to update both labels together.
if fromUserName.text == nil {
fromUserName.text = textFileld.text
replyToUserName.text = textFileld.text
}
A very broad example of an implementation you could use. Basically you should use the UITextFieldDelegate
. When a user finishes editing the textfield a call to textFieldDidEndEditing:
will be made and in this function you can update your labels.
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
var labelOne = UILabel()
var labelTwo = UILabel()
var myTextField = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
}
func textFieldDidEndEditing(textField: UITextField) {
if textField == myTextField {
labelOne.text = textField.text
labelTwo.text = textField.text
}
}
}
You can read more about UITextFieldDelegate
here
Upvotes: 0
Reputation: 305
If I understand your question correctly, you need to change the text of 2 UILabels whenever you editing the UITextField? If so, you should use the "Editing Began" or "Editing Changed" IBAction linked with your storyboard file. Then, have the UILabel's value change to whatever the UITextField's text is.
@IBAction textFileIdEditingChanged {
fromUsername.text = textFileId.text
replyToUserName.text = textFileId.text
}
Upvotes: 1
Reputation: 898
it seems fromUserName.text is an empty string so you should change to :
func labelTextChanger() {
if fromUserName.text != "" {
fromUserName.text = textFileld.text
} else {
replyToUserName.text = textFileld.text
}
}
Upvotes: 0
Reputation: 27448
Try this one,
func labelTextChanger() {
if fromUserName.text?.characters.count > 0 {
fromUserName.text = textFileld.text
} else {
replyToUserName.text = textFileld.text
}
}
Because it will return nil only when it's not exists in memory. so, it can't be nil
.
Upvotes: 0