UITextField Extensions
If you’re reading this, then I assume you’re familiar with Swift Extensions. Swift Extensions add new functionality to an existing class, structure, enumeration, or protocol type. Remember, it can only add new functionality but overriding existing functionality not possible with extensions. Here I am going to share some useful UITextField Extensions.
-
Extension to Check whether it has valid email id or not
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public extension UITextField { public var hasValidEmail: Bool { return text!.range(of: "(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}" + "~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\" + "x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-" + "z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5" + "]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-" + "9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21" + "-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])", options: String.CompareOptions.regularExpression, range: nil, locale: nil) != nil } } |
How to use this extension:
12 txtField.text = "Abc..123@example.com"print("Check Email: Abc..123@example.com -- ", txtField.hasValidEmail)
-
Change Placeholder Color
1 2 3 4 5 6 7 8 9 10 |
extension UITextField{ @IBInspectable var placeHolderColor: UIColor? { get { return self.placeHolderColor } set { self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: newValue!]) } } } |
How to use this extension:
Select TextField in Storyboard and Press key ⌘⌥+4 – for Attributes Inspector, you will find a new option for placeholder color
-
Set Left or Right Padding Space in TextField
1 2 3 4 5 6 7 8 9 10 11 12 |
extension UITextField { func setLeftPaddingPoints(_ amount:CGFloat){ let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height)) self.leftView = paddingView self.leftViewMode = .always } func setRightPaddingPoints(_ amount:CGFloat) { let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height)) self.rightView = paddingView self.rightViewMode = .always } } |
How to use this extension:
12345 txtField.setLeftPaddingPoints(50)//ortxtField.setRightPaddingPoints(50)
-
Set Bottom Border only
1 2 3 4 5 6 7 8 9 10 11 |
extension UITextField { func setBottomBorder(color:UIColor) { self.borderStyle = .none self.layer.backgroundColor = UIColor.white.cgColor self.layer.masksToBounds = false self.layer.shadowColor = color.cgColor self.layer.shadowOffset = CGSize(width: 0.0, height: 1.0) self.layer.shadowOpacity = 1.0 self.layer.shadowRadius = 0.0 } } |
How to use this extension:
1 txtField.setBottomBorder(color: UIColor.darkGray)
-
Add Done Button on inputAccessoryView of TextField
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
extension UITextField { @IBInspectable var doneAccessory: Bool{ get{ return self.doneAccessory } set(hasDone){ if hasDone{ addDoneButtonOnKeyboard() } } } func addDoneButtonOnKeyboard() { let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50)) doneToolbar.barStyle = .default let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction)) let items = [flexSpace, done] doneToolbar.items = items doneToolbar.sizeToFit() self.inputAccessoryView = doneToolbar } @objc func doneButtonAction(){ self.resignFirstResponder() } } |
How to use this extension:
1 txtField.addDoneButtonOnKeyboard()
-
Handle Multiple UITextFields like Signup form (Next and done return type)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
extension UITextField { class func connectAllTxtFieldFields(txtfields:[UITextField]) -> Void { guard let last = txtfields.last else { return } for i in 0 ..< txtfields.count - 1 { txtfields[i].returnKeyType = .next txtfields[i].addTarget(txtfields[i+1], action: #selector(UIResponder.becomeFirstResponder), for: .editingDidEndOnExit) } last.returnKeyType = .done last.addTarget(last, action: #selector(UIResponder.resignFirstResponder), for: .editingDidEndOnExit) } } |
How to use this extension:
1 UITextField.connectAllTxtFieldFields(txtfields: [txtField, txtField2, txtField3])
-
Restrict the number of characters to type in UITextFields
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
private var KeyMaxLength: Int = 0 extension UITextField { @IBInspectable var maxLength: Int { get { if let length = objc_getAssociatedObject(self, &KeyMaxLength) as? Int { return length } else { return Int.max } } set { objc_setAssociatedObject(self, &KeyMaxLength, newValue, .OBJC_ASSOCIATION_RETAIN) addTarget(self, action: #selector(checkMaxLength), for: .editingChanged) } } @objc func checkMaxLength(textField: UITextField) { guard let prospectiveText = self.text, prospectiveText.count > maxLength else { return } let selection = selectedTextRange let maxCharIndex = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength) text = prospectiveText.substring(to: maxCharIndex) selectedTextRange = selection } } |
How to use this extension:
Select UITextField in Storyboard and Press key ⌘⌥+4 – for Attributes Inspector, you will find a new option for Max Length
-
Set Corner Radius, Border Width, Border Color and Shadow Radius for UITextField
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
extension UITextField{ @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } @IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var borderColor: UIColor? { get { let color = UIColor.init(cgColor: layer.borderColor!) return color } set { layer.borderColor = newValue?.cgColor } } @IBInspectable var shadowRadius: CGFloat { get { return layer.shadowRadius } set { layer.shadowColor = UIColor.black.cgColor layer.shadowOffset = CGSize(width: 0, height: 2) layer.shadowOpacity = 0.4 layer.shadowRadius = shadowRadius } } } |
How to use this extension:
Select UITextField in Storyboard and Press key ⌘⌥+4 – for Attributes Inspector, you will find a new option for Corner Radius, Border Width, Border Color and Shadow Radius