×

iOS UITextField


UITextField is used to design textField. For Example , "Email" , "Password" or anything.

Important Properties :-

1) .text
2) .font
3) .numberOfLines
4) .lineBreakMode
5) .textColor
6) .backgroundColor
7) .textAlignment
8) .autoCorrectionType
9) .keyboardtype
10) .returnKeyType
11) .clearButtonMode
12) .userInteractionEnabled
13) .enabled

Example :-

import UIKit
var nameTextField = UITextField()
class ViewController: UIViewController {
    
    override func viewDidLoad()
     {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.init(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0)

        nameTextField = UITextField(frame:CGRect(x: nameLabel.frame.size.width + 12 , y: 44 , width: 200 , height: 32))
        nameTextField.textAlignment = NSTextAlignment.center
        self.view.addSubview(nameTextField)
        nameTextField.placeholder = "Email"
        nameTextField.layer.borderWidth = 1
        nameTextField.textColor = UIColor.black
        nameTextField.layer.cornerRadius = 2.0
        nameTextField.becomeFirstResponder()
        nameTextField.clearButtonMode = .whileEditing
        nameTextField.keyboardType = UIKeyboardType.namePhonePad

     }
 }

Below Code itself is self explanatory. Firstly , we initialized a "nameTextField".Then added it to self.view and assigned it some placeholder and given textColor with "UIColor" class .

To give border Color and border width you can use layer Property as shown in example.

Output :-



UITextField with clear Button Mode



 emailTextField.clearButtonMode = UITextFieldViewModeWhileEditing;

.clearButtonMode property of UITextField is used to enable clear button while you start Editing. Remember While Editing :)

Delegates of Text Field :-

We will use it later when we perform search in later examples. These are the most used delegates of textField you must know.

// UITextField Delegates
    func textFieldDidBeginEditing(_ textField: UITextField) {
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
    }
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        return true;
    }
    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        return true;
    }
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        return true;
    }
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        return true;
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder();
        return true;
    }