[ios] Create space at the beginning of a UITextField

I want to leave a bit of space at the beginning of a UITextField, just like here: Add lefthand margin to UITextField

But I don't know how to do that with Swift.

This question is related to ios swift cocoa-touch uitextfield

The answer is


I prefer to use IBDesignable class and IBInspectable properties to allow me to set the padding via Xcode storyboards and keep it reusable. I've also updated the code to work in Swift 4.

import Foundation
import UIKit

@IBDesignable
class PaddableTextField: UITextField {

    var padding = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0)

    @IBInspectable var left: CGFloat = 0 {
        didSet {
            adjustPadding()
        }
    }

    @IBInspectable var right: CGFloat = 0 {
        didSet {
            adjustPadding()
        }
    }

    @IBInspectable var top: CGFloat = 0 {
        didSet {
            adjustPadding()
        }
    }

    @IBInspectable var bottom: CGFloat = 0 {
        didSet {
            adjustPadding()
        }
    }

    func adjustPadding() {
         padding = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)

    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
    }

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: UIEdgeInsets(top: top, left: left, bottom: bottom, right: right))
    }

    override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: UIEdgeInsets(top: top, left: left, bottom: bottom, right: right))
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
         return bounds.inset(by: UIEdgeInsets(top: top, left: left, bottom: bottom, right: right))
    }
}

This one line of code saved me:

For Xamarin.iOS:

textField.Layer.SublayerTransform = CATransform3D.MakeTranslation(5, 0, 0);

For Swift:

textField.layer.sublayerTransform = CATransform3DMakeTranslation(5, 0, 0);

Here is Haagenti's answer updated to Swift 4.2:

class PaddedTextField: UITextField {

    func getPadding(plusExtraFor clearButtonMode: ViewMode) -> UIEdgeInsets {
        var padding = UIEdgeInsets(top: 11, left: 16, bottom: 11, right: 16)

        // Add additional padding on the right side when showing the clear button
        if self.clearButtonMode == .always || self.clearButtonMode == clearButtonMode {
            padding.right = 28
        }

        return padding
    }

    override open func textRect(forBounds bounds: CGRect) -> CGRect {
        let padding = getPadding(plusExtraFor: .unlessEditing)
        return bounds.inset(by: padding)
    }

    override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        let padding = getPadding(plusExtraFor: .unlessEditing)
        return bounds.inset(by: padding)
    }

    override open func editingRect(forBounds bounds: CGRect) -> CGRect {
        let padding = getPadding(plusExtraFor: .whileEditing)
        return bounds.inset(by: padding)
    }

}

Reference: Upgrading To Swift 4.2.

Edit: Account for clear button.


//MARK:-  Use this class for different type of Roles

import UIKit

class HelperExtensionViewController: UIViewController {

}

//MARK:- Extension

extension UIImageView
{
    func setImageCornerRadius()
    {
        self.layer.cornerRadius = self.frame.size.height/2
        self.clipsToBounds = true
    }

    func setImageCornerRadiusInPoints(getValue:CGFloat)
    {
        self.layer.cornerRadius = getValue
        self.clipsToBounds = true
    }
}

extension UIButton
{
    func setButtonCornerRadiusOnly()
    {
        self.layer.cornerRadius = self.frame.size.height/2
        self.clipsToBounds = true
    }

    func setBtnCornerRadiusInPoints(getValue:CGFloat)
    {
        self.layer.cornerRadius = getValue
        self.clipsToBounds = true
    }


}

extension UITextField
{
    func setTextFieldCornerRadiusWithBorder()
    {
        self.layer.cornerRadius = self.frame.size.height/2
        self.layer.borderColor = UIColor.darkGray.cgColor
        self.backgroundColor = UIColor.clear
        self.layer.borderWidth = 0.5
        self.clipsToBounds = true
    }

    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
    }
}



extension UIView
{

    func setCornerRadius()
    {
        self.layer.cornerRadius = self.frame.size.height/2
        self.clipsToBounds = true
    }

    // OUTPUT 1
    func setViewCornerRadiusWithBorder()
    {
        self.layer.cornerRadius = self.frame.size.height/2
        self.layer.borderColor = UIColor.init(red: 95.0/255.0, green: 229.0/255.0, blue: 206.0/255.0, alpha: 1.0).cgColor
        self.backgroundColor = UIColor.clear
        self.layer.borderWidth = 1.0
        self.clipsToBounds = true
    }

    func layoutSubviews(myView:UIView)
    {
        let shadowPath = UIBezierPath(rect: myView.bounds)
        myView.layer.masksToBounds = false
        myView.layer.shadowColor = UIColor.lightGray.cgColor
        myView.layer.shadowOffset = CGSize(width: -1.0, height: 2.0)
        myView.layer.shadowOpacity = 0.5
        myView.layer.shadowPath = shadowPath.cgPath
    }

    func layoutSubviews2(myView:UIView)
    {
        let shadowPath = UIBezierPath(rect: myView.bounds)
        myView.clipsToBounds = true
        myView.layer.masksToBounds = false
        myView.layer.shadowColor = UIColor.black.cgColor
        myView.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
        myView.layer.shadowOpacity = 0.2
        myView.layer.shadowPath = shadowPath.cgPath

    }

    func setViewCornerRadiusInPoints(getValue:CGFloat)
    {
        self.layer.cornerRadius = getValue
        self.clipsToBounds = true
    }


    func dropShadow(scale: Bool = true) {
        layer.masksToBounds = false
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOpacity = 0.5
        layer.shadowOffset = CGSize(width: -1, height: 1)
        layer.shadowRadius = 1

        layer.shadowPath = UIBezierPath(rect: bounds).cgPath
        layer.shouldRasterize = true
        layer.rasterizationScale = scale ? UIScreen.main.scale : 1
    }

    // OUTPUT 2
    func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize, radius: CGFloat = 1, scale: Bool = true) {
        layer.masksToBounds = false
        layer.shadowColor = color.cgColor
        layer.shadowOpacity = opacity
        layer.shadowOffset = offSet
        layer.shadowRadius = radius

        layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
        layer.shouldRasterize = true
        layer.rasterizationScale = scale ? UIScreen.main.scale : 1
    }

    func setGradientBackground(myview:UIView) {
        let colorTop =  UIColor(red: 100.0/255.0, green: 227.0/255.0, blue: 237.0/255.0, alpha: 1.0).cgColor
        let colorBottom = UIColor(red: 141.0/255.0, green: 109.0/255.0, blue: 164.0/255.0, alpha: 1.0).cgColor

        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [colorTop, colorBottom]
        gradientLayer.locations = [1.0, 1.0]
        gradientLayer.frame = myview.bounds

        myview.layer.insertSublayer(gradientLayer, at:0)
    }
}

* Extending UITextField in Swift 5 *

import UIKit

@IBDesignable
extension UITextField {

    @IBInspectable var paddingLeftCustom: CGFloat {
        get {
            return leftView!.frame.size.width
        }
        set {
            let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
            leftView = paddingView
            leftViewMode = .always
        }
    }

    @IBInspectable var paddingRightCustom: CGFloat {
        get {
            return rightView!.frame.size.width
        }
        set {
            let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
            rightView = paddingView
            rightViewMode = .always
        }
    }

}

Such margin can be achieved by setting leftView / rightView to UITextField.

Updated For Swift 4

// Create a padding view for padding on left
textField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: textField.frame.height))
textField.leftViewMode = .always

// Create a padding view for padding on right
textField.rightView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: textField.frame.height))
textField.rightViewMode = .always

I just added/placed an UIView to left and right side of the textfield. So now the typing will start after the view.

Thanks

Hope this helped...


Easy way: to do this by extending UITextField

extension UITextField {

   func setPadding(left: CGFloat? = nil, right: CGFloat? = nil){
       if let left = left {
          let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: left, height: self.frame.size.height))
          self.leftView = paddingView
          self.leftViewMode = .always
       }

       if let right = right {
           let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: right, height: self.frame.size.height))
           self.rightView = paddingView
           self.rightViewMode = .always
       }
   }

}

Then you can set padding to any edge this way:

textField.setPadding(left: 5, right: 5)

Simple swift 3 solution - add code to viewDidLoad:

let indentView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 20))
textField.leftView = indentView
textField.leftViewMode = .always

No need for ridiculously long code


ScareCrow's answer in Swift 3

let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5);

override func textRect(forBounds bounds: CGRect) -> CGRect {
    return UIEdgeInsetsInsetRect(bounds, padding)
}

override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
    return UIEdgeInsetsInsetRect(bounds, padding)
}

override func editingRect(forBounds bounds: CGRect) -> CGRect {
    return UIEdgeInsetsInsetRect(bounds, padding)
}

Put this code in your viewDidLoad():

textField.delegate = self

let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: self.textField.frame.height))
textField.leftView = paddingView
textField.leftViewMode = UITextFieldViewMode.always

It works for me :)


Swift 4, Xcode 9

I like Pheepster's answer, but how about we do it all from the extension, without requiring VC code or any subclassing:

import UIKit

@IBDesignable
extension UITextField {

    @IBInspectable var paddingLeftCustom: CGFloat {
        get {
            return leftView!.frame.size.width
        }
        set {
            let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
            leftView = paddingView
            leftViewMode = .always
        }
    }

    @IBInspectable var paddingRightCustom: CGFloat {
        get {
            return rightView!.frame.size.width
        }
        set {
            let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
            rightView = paddingView
            rightViewMode = .always     
        }
    }
}

Use my extension Swift 5 tested:

extension UITextField {

enum PaddingSpace {
    case left(CGFloat)
    case right(CGFloat)
    case equalSpacing(CGFloat)
}

func addPadding(padding: PaddingSpace) {

    self.leftViewMode = .always
    self.layer.masksToBounds = true

    switch padding {

    case .left(let spacing):
        let leftPaddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
        self.leftView = leftPaddingView
        self.leftViewMode = .always

    case .right(let spacing):
        let rightPaddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
        self.rightView = rightPaddingView
        self.rightViewMode = .always

    case .equalSpacing(let spacing):
        let equalPaddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
        // left
        self.leftView = equalPaddingView
        self.leftViewMode = .always
        // right
        self.rightView = equalPaddingView
        self.rightViewMode = .always
    }
}
}

How to use

// equal padding
yourTextField.addPadding(padding: .equalSpacing(10)) 

// padding right 
yourTextField.addPadding(padding: .right(10))

// padding left
yourTextField.addPadding(padding: .left(10)) 

To Extend original answer for leftView and Swift5+

class TextField: UITextField {

let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
override open func textRect(forBounds bounds: CGRect) -> CGRect {
    let paddedRect = bounds.inset(by: self.padding)
    if (self.leftViewMode == .always || self.leftViewMode == .unlessEditing) {
        return self.adjustRectOriginForLeftView(bounds: paddedRect)
    }
    return paddedRect
}
override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
    let paddedRect = bounds.inset(by: self.padding)
    if (self.leftViewMode == .always || self.leftViewMode == .unlessEditing) {
        return self.adjustRectOriginForLeftView(bounds: paddedRect)
    }
    return paddedRect;
}
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
    let paddedRect = bounds.inset(by: self.padding);
    if (self.leftViewMode == .always || self.leftViewMode == .unlessEditing) {
        return self.adjustRectOriginForLeftView(bounds: paddedRect)
    }
    return paddedRect;
}

func adjustRectOriginForLeftView(bounds : CGRect) -> CGRect{
    var paddedRect = bounds;
    paddedRect.origin.x += self.leftView!.frame.width
    return paddedRect
    
}

}


To create padding view for UITextField in Swift 5

func txtPaddingVw(txt:UITextField) {
    let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 5, height: 5))
    txt.leftViewMode = .always
    txt.leftView = paddingView
}

Subclassing UITextField is the way to go. Open a playground and add the following code:

class MyTextField : UITextField {
    var leftTextMargin : CGFloat = 0.0

    override func textRectForBounds(bounds: CGRect) -> CGRect {
        var newBounds = bounds
        newBounds.origin.x += leftTextMargin
        return newBounds
    }

    override func editingRectForBounds(bounds: CGRect) -> CGRect {
        var newBounds = bounds
        newBounds.origin.x += leftTextMargin
        return newBounds
    }
}

let tf = MyTextField(frame: CGRect(x: 0, y: 0, width: 100, height: 44))
tf.text = "HELLO"
tf.leftTextMargin = 25
tf.setNeedsLayout()
tf.layoutIfNeeded()

Create UIView with required padding space and add it to textfield.leftView member and set textfield.leftViewMode member to UITextFieldViewMode.Always

// For example if you have textfield named title
@IBOutlet weak var title: UITextField!
// Create UIView 
let paddingView : UIView = UIView(frame: CGRectMake(0, 0, 5, 20))
//Change your required space instaed of 5.
title.leftView = paddingView
title.leftViewMode = UITextFieldViewMode.Always

in Swift 4.2 and Xcode 10

Initially my text field is like this.

enter image description here

After adding padding in left side my text field is...

enter image description here

//Code for left padding 
textFieldName.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: textFieldName.frame.height))
textFieldName.leftViewMode = .always

Like this we can create right side also.(textFieldName.rightViewMode = .always)

If you want SharedInstance type code(Write once use every ware) see the below code.

//This is my shared class
import UIKit
class SharedClass: NSObject {
    static let sharedInstance = SharedClass()

    //This is my padding function.
    func textFieldLeftPadding(textFieldName: UITextField) {
    // Create a padding view
    textFieldName.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 3, height: textFieldName.frame.height))
    textFieldName.leftViewMode = .always//For left side padding
    textFieldName.rightViewMode = .always//For right side padding
    }

    private override init() {

    }
}

Now call this function like this.

//This single line is enough
SharedClass.sharedInstance.textFieldLeftPadding(textFieldName:yourTF)

If you use an extension, there is no need to subclass UITextField and the new functionality will be made available to any UITextField in your app:

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
    }
}

When I need to set the padding of a text field anywhere in my application, I simply do the following:

    textField.setLeftPaddingPoints(10)
    textField.setRightPaddingPoints(10)

Using Swift extensions, the functionality is added to the UITextField directly without subclassing.

Hope this helps!


X, Y , Z are your desired values

textField.layer.sublayerTransform = CATransform3DMakeTranslation(x, y, z)

In Swift 3. You may use custom UITextField with indent that is set in its constructor. Don't need for extra declaration in a controller.

class CustomTextField : UITextField {

private let indentView = UIView(frame: CGRect(x: 0, y:0, width: 10, height: 10))

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.leftView = indentView
    self.leftViewMode = .always 
        }
}

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to cocoa-touch

Include of non-modular header inside framework module Move textfield when keyboard appears swift Create space at the beginning of a UITextField Navigation bar with UIImage for title Generate a UUID on iOS from Swift How do I write a custom init for a UIView subclass in Swift? creating custom tableview cells in swift How would I create a UIAlertView in Swift? Get current NSDate in timestamp format How do you add an in-app purchase to an iOS application?

Examples related to uitextfield

Keep placeholder text in UITextField on input in IOS Set the maximum character length of a UITextField in Swift How to restrict UITextField to take only numbers in Swift? Disabling user input for UITextfield in swift How do I check when a UITextField changes? Swift add icon/image in UITextField Move textfield when keyboard appears swift Create space at the beginning of a UITextField Max length UITextField How to hide keyboard in swift on pressing return key?