Create space at the beginning of a UITextField
Asked Answered
E

23

202

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.

Emulsifier answered 18/8, 2014 at 16:4 Comment(4)
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: developer.apple.com/library/prerelease/ios/documentation/Swift/…Doelling
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.Langille
the padding view would just be a vanilla UIView that has the width that you would likeDoelling
For Swift 5: textField.layoutMargins.left = 20Histone
A
344

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;
}
Armistead answered 21/11, 2014 at 17:13 Comment(6)
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.Ruhr
@Mr.UB Check what platform the current device is and create different padding based on that. #4568228. Probably with something like thisArmistead
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.Shout
If your text field is multiple lines, this makes the placeholder text centered and supercedes textAlignment = .left and contentVerticalAlignment = .topAldosterone
Swift 5: textField.layoutMargins.left = 20Histone
IF YOU ALSO NEED AN ICON ON THE LEFT: https://mcmap.net/q/129464/-swift-add-icon-image-in-uitextfield full solution to copy pasteFrausto
S
288

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

Subgroup answered 16/11, 2016 at 16:6 Comment(5)
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.Huggins
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.Inviolable
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.Poundfoolish
how to set in UILabel ?Roberson
Fave solution and removes the need to repeat the same code through each VCDisputation
M
70

X, Y , Z are your desired values

textField.layer.sublayerTransform = CATransform3DMakeTranslation(x, y, z)
Massenet answered 5/2, 2016 at 9:28 Comment(3)
This does not seem to work with textField.clearButtonMode = UITextFieldViewMode.Always – the clear button is moved to the right as wellRhizobium
Does not work when Clear button needs to be shown...the clear button is moved as well.Natatorial
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 eitherArmistead
A
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...

Annihilator answered 19/10, 2015 at 6:8 Comment(3)
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;Inceptive
This solution is much cleaner than the subclassing mentioned above. Subclassing should be avoided as much as possible. I suggest the following reading krakendev.io/blog/subclassing-can-suck-and-heres-whyPudgy
be careful, this will prevent the clearButton from being displayed (if you using it)Kristofer
H
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     
        }
    }
}
Haricot answered 29/11, 2017 at 11:59 Comment(3)
It'd be safer to do rightView?.frame.size.width ?? 0Pabulum
It might. I, for myself, don't ever call the getter so it doesn't bother me.Haricot
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.Haricot
J
31

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)) 
Jordanjordana answered 19/2, 2020 at 15:33 Comment(4)
@JoséRaúlToledanoR THX :)Jordanjordana
Elegant. Thank you.Chaperon
@Chaperon Grazie mille Carlo :)Jordanjordana
This is the best solution.Nibelungenlied
T
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)
Thump answered 18/7, 2018 at 13:25 Comment(4)
Shouldn't extension work better rather than introducing a shared class for such a minor task ?Approximation
@ Sharkes Monken , I con't understoodThump
@ Sharkes Monken, can u please explain it for me. Thank you.Thump
I think it mean extension UITextField for the function, singleton for this helper func is not goodHaug
M
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

Maharajah answered 10/2, 2017 at 20:1 Comment(2)
This does not work for UITextField inside a UISearchBar. :( I need the solution that works specifically in that case :(Creationism
@Maharajah 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.Armistead
A
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);
Alephnull answered 25/6, 2019 at 13:13 Comment(0)
W
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
}
Weitzman answered 21/3, 2017 at 11:33 Comment(0)
E
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.

Extramundane answered 28/10, 2018 at 13:57 Comment(0)
T
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()
Taciturnity answered 18/8, 2014 at 20:29 Comment(2)
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 fieldArmistead
if left is 25 width should be minus 50 to have equal paddingArmistead
D
8

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
    }
}
Depersonalization answered 20/7, 2021 at 16:38 Comment(0)
Q
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)
Quasijudicial answered 16/5, 2018 at 20:4 Comment(1)
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 visibleHiggs
C
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
Conyers answered 21/4, 2016 at 14:36 Comment(0)
C
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))
    }
}
Cheshire answered 2/12, 2018 at 3:43 Comment(0)
B
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 :)

Blanding answered 13/10, 2017 at 13:6 Comment(0)
P
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)
}
Patent answered 22/12, 2016 at 10:35 Comment(0)
I
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 
        }
}
Implicative answered 13/3, 2017 at 13:32 Comment(0)
V
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
        }
    }

}
Valid answered 26/5, 2019 at 23:31 Comment(0)
J
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)
    }
}
Jacquez answered 20/12, 2019 at 5:59 Comment(0)
G
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
    
}

}

Gnotobiotics answered 17/9, 2020 at 17:28 Comment(0)
M
-7

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

textFieldName.setLeftPaddingPoints(CGFloat(10))  
textFieldName.setRightPaddingPoints(CGFloat(10)
Mizuki answered 7/3, 2021 at 23:1 Comment(1)
This does not exist. I think you are using an extension mentioned below to achieve this.Tetrameter

© 2022 - 2024 — McMap. All rights reserved.