iOS UI Controls

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  
				
			
By adding attributes, we can additionally personalize the text box, just like we’ve done with the label. In certain cases, we might also need to set up the keyboard—for instance, preventing the user from inputting just numbers. Textfield reports editing changes by using a delegate object and the target action method.
 
To configure the text field, follow these steps.
 
1.Look through the object library for the TextField, then drag the result onto the storyboard.
 
2.Set up a text field with one or more targets and actions.
 
3.Personalize the text field’s keyboard-related properties.
 
4.To report the modifications made during editing, complete text field delegate object duties.
 
a. When a user modifies the text field’s content, the text field delegate method is triggered.
 
b. verifying the text that the user entered.
 
c. Tapping the return button on the keyboard invokes the Delegate method.
 
5.Establish a text field outlet in the relevant ViewController class.

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.

iOS: TextField -

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.

iOS: TextField -

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.

iOS: TextField -

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

iOS: TextField -

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

SNMethod SignatureDescription
1func textFieldShouldBeginEditing(UITextField) -> BoolIt asks the delegate if editing should begin the respective textfield.
2func textFieldDidBeginEditing(UITextField)It tells the delegate that the editing is started in the textfield.
3func textFieldShouldEndEditing(UITextField) -> BoolIt asks the delegate to end the editing in the textfield.
4func textFieldDidEndEditing(UITextField, reason: UITextField.DidEndEditingReason)It tells the delegate that the editing has been stopped for the specified textfield.
5func textFieldDidEndEditing(UITextField)It is the overloaded methods which also does the same as the above.
6func textField(UITextField, shouldChangeCharactersIn: NSRange, replacementString: String) -> BoolIt asks the delegate that if the text field’s current content should be changed.
7func textFieldShouldClear(UITextField) -> BoolIt asks the delegate if the text field’s current content should be removed.

Interface builder Attributes

TextField Attributes

SNAttributeDescriptionProperty
1textIt represents the current text the textfiled contains. It can be accessed by the text property of the textfield at runtime.text
2colorIt represents the color of the textfield text. This can be accessed by using the textColor property of the TextField.textColor
3fontIt represents the font of the text field’s text. This can be accessed by using the font property of the textfield object.font
4alignmentIt represents the alignment of the text inside the editing area.textAlignment
5placeholderIt represents the placeholder string of the textfield. When the textfield is empty, this string is displayed to guide the user.placeholder
6backgroundIt represents the background image to display when the textfield is enabled. The background image is displayed behind the textfield content.background
7disabledIt represents the background image to display when the textfield is disabled.disabledBackground
8border styleIt represents the visual style of the textfield border.borderStyle
9clear buttonThe 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
10Min font sizeThe 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

SNAttributeDescriptionProperty
1CapitalizationThis attribute applies the automatic capitalization style to the typed text within the text field.autocapitalizationType
2CorrectionThis attribute is used to determine whether the auto-correction is enabled or not while typing.autocorrectionType
3Spell CheckingIt is used to determine whether the spelling checking enabled or not while typing.spellCheckingType
4Keyboard TypeThis property sets the type of the keyboard displayed while typing.keyboardType
5AppearanceIt is used to set the appearance of the textfield. It specifies a dark or light keyboard.keyboardAppearance
6Return KeyIt is used to set the type of the return key to display on the keyboard.returnKeyType
Share this Doc

iOS: TextField

Or copy link

Explore Topic