iOS: TextField
It can be characterized as an object that is utilized in the interface to show an editable text field. Textfields are used to collect user input that is text-based.
class UITextField : UIControl
Example
Here, we’ll use text fields and labels to create a form. Additionally, we will apply a few validations to the text box. The user will see an alert if the validation is unsuccessful and a success message if it is successful.
Interface builder
We will utilize text fields to collect data from the user and associate it with labels to display messages to the user in order to develop the project’s interface.
Since this tutorial hasn’t yet addressed buttons, we won’t be using them in the program; instead, clickable labels will cause the events to occur.
Locate the necessary objects in the object library to create the interface, then drag the finished product into the storyboard.
To collect data from the user, the project creates the view below.
How to show the success message on the successful registration?
In iOS development, once a task is successfully finished, we often generate another screen. In this instance, though, the success message will be contained in a UIView that is created on the same screen and hidden until the validation is successful and the submit label is tapped.
The next image displays the interface following the addition of the createUserSuccessView.
Outlets
The items in the Associated View Controller class are used to generate the outlets. As seen in the accompanying image, the connection inspector in XCode displays all of the connecting outlets.
ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var createUserSuccessView: UIView!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var mobileTextField: UITextField!
@IBOutlet weak var sbmtLbl: UILabel!
@IBOutlet weak var messageNameLbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setInitViews()
sbmtLbl.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(sbmtBtnTapped(sender:)))
sbmtLbl.addGestureRecognizer(tap)
}
func setInitViews(){
nameTextField.becomeFirstResponder()
emailTextField.delegate = self
mobileTextField.delegate = self
nameTextField.delegate = self
passwordTextField.delegate = self
}
@objc func sbmtBtnTapped(sender: UITapGestureRecognizer){
if(nameTextField.text?.isEmpty ?? false || emailTextField.text?.isEmpty ?? false || passwordTextField.text?.isEmpty ?? false || passwordTextField.text?.isEmpty ?? false){
let alert = UIAlertController(title: nil, message: "Please fill all the details", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default) { (action) in
self.dismiss(animated: true, completion: nil)
}
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
else{
messageNameLbl.text = "Hi " + (nameTextField.text ?? "")
createUserSuccessView.isHidden = false
}
}
}
extension ViewController:UITextFieldDelegate{
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if(textField == mobileTextField){
let currrentCharacterCount = textField.text?.count ?? 0
if range.length + range.location > currrentCharacterCount {
return false
}
let newLength = currrentCharacterCount + string.count - range.length
return newLength <= 10
}
else{
return true
}
}
}
Output
Configure the keyboard
By using the becomeFirstResponder() function on the text field outlet, the text field can take the lead in response. Keyboard input is connected to the text field and the keyboard automatically appears when the text field becomes the first responder. The text field becomes the first responder—that is, the keyboard is visible—when the user taps on it.
The text field outlet’s resignFirstResponder() function is called in order to close the keyboard. In reaction to some particular interactions, we might have to discard the keyboard. The return key is automatically used to dismiss the keyboard.
The keyboard’s presentation and dismissal have an impact on the textfield’s editing state. The textfield notifies its delegate in the proper way as soon as the user begins editing it when the keyboard appears. When editing starts and stops, the delegate methods are likewise informed.
TextField Delegate Methods
| SN | Method Signature | Description |
|---|---|---|
| 1 | func textFieldShouldBeginEditing(UITextField) -> Bool | It asks the delegate if editing should begin the respective textfield. |
| 2 | func textFieldDidBeginEditing(UITextField) | It tells the delegate that the editing is started in the textfield. |
| 3 | func textFieldShouldEndEditing(UITextField) -> Bool | It asks the delegate to end the editing in the textfield. |
| 4 | func textFieldDidEndEditing(UITextField, reason: UITextField.DidEndEditingReason) | It tells the delegate that the editing has been stopped for the specified textfield. |
| 5 | func textFieldDidEndEditing(UITextField) | It is the overloaded methods which also does the same as the above. |
| 6 | func textField(UITextField, shouldChangeCharactersIn: NSRange, replacementString: String) -> Bool | It asks the delegate that if the text field’s current content should be changed. |
| 7 | func textFieldShouldClear(UITextField) -> Bool | It asks the delegate if the text field’s current content should be removed. |
Interface builder Attributes
TextField Attributes
| SN | Attribute | Description | Property |
|---|---|---|---|
| 1 | text | It represents the current text the textfiled contains. It can be accessed by the text property of the textfield at runtime. | text |
| 2 | color | It represents the color of the textfield text. This can be accessed by using the textColor property of the TextField. | textColor |
| 3 | font | It represents the font of the text field’s text. This can be accessed by using the font property of the textfield object. | font |
| 4 | alignment | It represents the alignment of the text inside the editing area. | textAlignment |
| 5 | placeholder | It represents the placeholder string of the textfield. When the textfield is empty, this string is displayed to guide the user. | placeholder |
| 6 | background | It represents the background image to display when the textfield is enabled. The background image is displayed behind the textfield content. | background |
| 7 | disabled | It represents the background image to display when the textfield is disabled. | disabledBackground |
| 8 | border style | It represents the visual style of the textfield border. | borderStyle |
| 9 | clear button | The clear button is an overlay view that can be tapped by the user to delete all the content of the textfield. This attribute can be used to set the appearance of the clear button within the textfield. | clearButtonMode |
| 10 | Min font size | The minimum font size for the text field’s text. When the Adjust to Fit option is enabled, the text field automatically varies the font size to ensure maximum legibility of the text. | minFontSize |
Keyboard Attributes
| SN | Attribute | Description | Property |
|---|---|---|---|
| 1 | Capitalization | This attribute applies the automatic capitalization style to the typed text within the text field. | autocapitalizationType |
| 2 | Correction | This attribute is used to determine whether the auto-correction is enabled or not while typing. | autocorrectionType |
| 3 | Spell Checking | It is used to determine whether the spelling checking enabled or not while typing. | spellCheckingType |
| 4 | Keyboard Type | This property sets the type of the keyboard displayed while typing. | keyboardType |
| 5 | Appearance | It is used to set the appearance of the textfield. It specifies a dark or light keyboard. | keyboardAppearance |
| 6 | Return Key | It is used to set the type of the return key to display on the keyboard. | returnKeyType |