I have two textFields
on the screen and a Submit button
. User inputs details in first textField and then the second one.
My requirement is to end the editing when Submit button
is clicked and print the user inputs in these textFields
.I am having issues printing the second textField's value, as the editing never seems to end when the user clicks the Submit button
.
Here is my code. Appreciate your help on this issue (I have added the textfield delegate)
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
var firstName = ""
var lastName = ""
@IBOutlet var buttonUI: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func Submit(sender: UIButton) {
print(firstName)
print(lastName)
}
func textFieldDidEndEditing(textField: UITextField) {
switch textField.tag {
case 1:
firstName = textField.text!
print(firstName)
case 2:
lastName = textField.text!
print(lastName)
default: break
}
}
}
Within your
ViewController
class, for each textfield, create an @IBOutlet property by Ctrl-dragging each text field from the storyboard to your codeAlso create a private
UITextField
property to hold the (possibly) current (/most recently used) text field.Override the
viewDidLoad
method of yourUIViewController
subclass to initialize the delegates for the two "public" text field instancesMoreover, use the two
textFieldShouldReturn(...)
andtextFieldDidBeginEditing(...)
methods of theUITextFieldDelegate
to resign the (active) text fields status's as first responder and to update thecurrentTextField
reference, respectively.Finally, resign any possibly current text field as first responder, in case
submit
is pressed in-middle-of editingWith this, your view controller should work as intended.
To summarize: after the additions and modifications above, your
ViewController
class should look likeWhat do you mean by
Why not just read the values in textfields when the users presses submit? Make sure your outlets and delegates are correct.
Make an action to your button
Touch up inside
and in that button you´ll read the values: