198

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.

Community
  • 1
  • 1
LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
  • well, you can't subclass swift objects in Objective-C, but you can do it the other way around... So my guess you you just adjust the answer and combine it with: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WritingSwiftClassesWithObjective-CBehavior.html#//apple_ref/doc/uid/TP40014216-CH5-XID_56 – Grady Player Aug 18 '14 at 16:12
  • 2
    This is probably not the best solution, but you could make a uiview *paddingView and do `UITextField.leftView = paddingView`. so give the padding view your desired width. – ipalibowhyte Aug 18 '14 at 16:12
  • 1
    the padding view would just be a vanilla UIView that has the width that you would like – Grady Player Aug 18 '14 at 16:34
  • 1
    For Swift 5: textField.layoutMargins.left = 20 – J A S K I E R Feb 13 '20 at 09:41

23 Answers23

341

This is what I am using right now:

Swift 4.2, 5

class TextField: UITextField {

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

    override open func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: padding)
    }

    override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: padding)
    }

    override open func editingRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.inset(by: padding)
    }
}

Swift 4

class TextField: UITextField {

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

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

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

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

Swift 3:

class TextField: UITextField {
    
    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)
    }
}

I never set a other padding but you can tweak. This class doesn't take care of the rightView and leftView on the textfield. If you want that to be handle correctly you can use something like (example in objc and I only needed the rightView:

- (CGRect)textRectForBounds:(CGRect)bounds {
    CGRect paddedRect = UIEdgeInsetsInsetRect(bounds, self.insets);

    if (self.rightViewMode == UITextFieldViewModeAlways || self.rightViewMode == UITextFieldViewModeUnlessEditing) {
        return [self adjustRectWithWidthRightView:paddedRect];
    }
    return paddedRect;
}

- (CGRect)placeholderRectForBounds:(CGRect)bounds {
    CGRect paddedRect = UIEdgeInsetsInsetRect(bounds, self.insets);

    if (self.rightViewMode == UITextFieldViewModeAlways || self.rightViewMode == UITextFieldViewModeUnlessEditing) {
        return [self adjustRectWithWidthRightView:paddedRect];
    }
    return paddedRect;
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    CGRect paddedRect = UIEdgeInsetsInsetRect(bounds, self.insets);

    if (self.rightViewMode == UITextFieldViewModeAlways || self.rightViewMode == UITextFieldViewModeWhileEditing) {
        return [self adjustRectWithWidthRightView:paddedRect];
    }
    return paddedRect;
}

- (CGRect)adjustRectWithWidthRightView:(CGRect)bounds {
    CGRect paddedRect = bounds;
    paddedRect.size.width -= CGRectGetWidth(self.rightView.frame);

    return paddedRect;
}
Haagenti
  • 7,974
  • 5
  • 38
  • 52
  • Why are you doubling the top and left insets when calculating width and height? Shouldn't need to do that. You should add the two relevant insets together and subtract the total from the original bounds. Or just subtract both in sequence. – Ash May 26 '15 at 16:05
  • 1
    @Mr.UB Check what platform the current device is and create different padding based on that. http://stackoverflow.com/questions/4567728/is-this-the-proper-way-to-detect-an-ipad. Probably with something like this – Haagenti Mar 14 '16 at 11:48
  • Apple provides the equivalent of the `newBounds` method with the `UIEdgeInsetsInsetRect` function. Instead of `return self.newBounds(bounds)` you could use `return UIEdgeInsetsInsetRect(bounds, padding)` and remove the `newBounds` method. – Mobile Dan Apr 11 '16 at 17:31
  • If your text field is multiple lines, this makes the placeholder text centered and supercedes textAlignment = .left and contentVerticalAlignment = .top – Code Wiget Jul 09 '19 at 20:21
  • Swift 5: textField.layoutMargins.left = 20 – J A S K I E R Feb 13 '20 at 09:40
  • **IF YOU ALSO NEED AN ICON ON THE LEFT:** https://stackoverflow.com/a/61870553/294884 full solution to copy paste – Fattie May 18 '20 at 13:22
283

This is a great case for an extension. By using 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.

starball
  • 20,030
  • 7
  • 43
  • 238
Pheepster
  • 6,045
  • 6
  • 41
  • 75
  • 10
    Excellent solution, very elegant. The only change I made was that I added them into one function so I get something like textField.setPaddingFor(left: 10, right: 10). Both params, are optional hence if you pass nil the padding will be 0. – Nermin Sehic Dec 10 '16 at 20:33
  • 5
    Great! But If you set textField.clearButtonMode = .always, you have to set only the left padding. The right padding will move the clear button to the right. – Peter Kreinz Dec 30 '16 at 14:45
  • 3
    One observation. It's more like a leading/trailing padding. But, the weird thing is that it responses to the textfield text alignment!! not the app language direction. – hasan Oct 06 '17 at 23:18
  • how to set in UILabel ? – Innocent Mar 11 '20 at 12:19
  • Fave solution and removes the need to repeat the same code through each VC – Chris Jan 22 '23 at 14:08
70

X, Y , Z are your desired values

textField.layer.sublayerTransform = CATransform3DMakeTranslation(x, y, z)
ak2g
  • 1,673
  • 15
  • 22
  • 12
    This does not seem to work with textField.clearButtonMode = UITextFieldViewMode.Always – the clear button is moved to the right as well – CaptainProton Sep 13 '16 at 17:18
  • 1
    Does not work when Clear button needs to be shown...the clear button is moved as well. – xdev Jan 02 '17 at 02:45
  • This anwer is short but not complete and might bug out later. @Adrian you have a great point, but this is not the way. The reason you've to do it with a subclass is for all the edge cases. This code will probably crash before the subclass solution. But you are right that you shouldn't write code that is not strictly needed and can be provide by using the given libraries, but you shouldn't abuse the standard libraries either – Haagenti Jun 09 '17 at 10:43
65

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

onCompletion
  • 6,500
  • 4
  • 28
  • 37
  • 2
    if someone needed in "objective c" here is the code, UIView* paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, self. userNameTxtFldOutlet.frame.size.height)]; self. userNameTxtFldOutlet.leftView = paddingView; self. userNameTxtFldOutlet.leftViewMode = UITextFieldViewModeAlways; – Avaan Apr 12 '16 at 07:09
  • 1
    This solution is much cleaner than the subclassing mentioned above. Subclassing should be avoided as much as possible. I suggest the following reading https://krakendev.io/blog/subclassing-can-suck-and-heres-why – Sylvain Jun 17 '20 at 15:50
  • be careful, this will prevent the clearButton from being displayed (if you using it) – zslavman Apr 16 '21 at 15:43
39

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     
        }
    }
}
Teodor Ciuraru
  • 3,417
  • 1
  • 32
  • 39
  • It'd be safer to do `rightView?.frame.size.width ?? 0` – Tal Dec 01 '17 at 18:44
  • It might. I, for myself, don't ever call the getter so it doesn't bother me. – Teodor Ciuraru Dec 02 '17 at 09:08
  • 2
    Guys, I modified the methods' names from `paddingLeft` to `paddingLeftCustom` and the other one too. If I haven't done this, a bug that followed me two weeks would've appeared when you were using Views that do have a UITextView (like UISearchBar). Just... don't set the default names. – Teodor Ciuraru Feb 13 '18 at 20:20
30

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)) 
Lucas
  • 6,675
  • 3
  • 25
  • 43
Fabio
  • 5,432
  • 4
  • 22
  • 24
21

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)
Naresh
  • 16,698
  • 6
  • 112
  • 113
14

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

livtay
  • 553
  • 4
  • 9
  • This does not work for UITextField inside a UISearchBar. :( I need the solution that works specifically in that case :( – Miki Jan 09 '18 at 14:41
  • @livtay This will not work when you use clearButtonMode or want to have an leftView, etc. This is a quick win though but just be aware the hole you're going in. – Haagenti Jan 16 '18 at 09:13
11

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);
LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
Shanu Singh
  • 365
  • 3
  • 16
10

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
}
Hardik Thakkar
  • 15,269
  • 2
  • 94
  • 81
10

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.

CartoonChess
  • 663
  • 7
  • 17
8

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()
  • This is almost perfect. You probably have a placeholder which has a like wise method: "placeholderRectForBounds" which you should also override and what you add as an x should be subtracted from the width otherwise you can't see you what type when the text goes beyond the length of the field – Haagenti Nov 21 '14 at 17:02
  • if left is 25 width should be minus 50 to have equal padding – Haagenti Nov 21 '14 at 17:10
7

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)
Musa almatri
  • 5,596
  • 2
  • 34
  • 33
  • try the same code but with colored -left- and -right- views on iOS 13 and build it with xCode 11 .... )) you will be surprised about how the textView changes it`s insets and hot it moves the views towards the edges so the added views are not fully visible – Massmaker Oct 02 '19 at 12:15
7

In most cases you can regard this as a technicality but all the examples don't get the difference between frame and bounds right. When referencing the view's height in a subview, use bounds – otherwise you may run into trouble once some transform is applied to the parent.
See the updated code below (based on Pheepster's answer).

extension UITextField {

    func setLeftPadding(_ amount: CGFloat = 10) {

        let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.bounds.size.height))
        self.leftView = paddingView
        self.leftViewMode = .always
    }

    func setRightPadding(_ amount: CGFloat = 10) {

        let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.bounds.size.height))
        self.rightView = paddingView
        self.rightViewMode = .always
    }
}
de.
  • 7,068
  • 3
  • 40
  • 69
6

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
PAC
  • 1,664
  • 1
  • 18
  • 24
6

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))
    }
}
Payne Miller
  • 134
  • 1
  • 8
5

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 :)

LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
D.Garcia
  • 71
  • 1
  • 1
4

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)
}
spogebob92
  • 1,474
  • 4
  • 23
  • 32
4

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 
        }
}
Photon Point
  • 798
  • 2
  • 13
  • 23
2

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

}
Emil Georgiev
  • 529
  • 4
  • 15
1
//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)
    }
}
Davender Verma
  • 503
  • 2
  • 12
0

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
    
}

}

Saqibdb
  • 73
  • 1
  • 8
-7

Create space at the beginning of a UITextField.
in Swift 5+ and Xcode 12.

textFieldName.setLeftPaddingPoints(CGFloat(10))  
textFieldName.setRightPaddingPoints(CGFloat(10)
Ali Subhani
  • 169
  • 1
  • 7