About the author

Related Articles

29 Comments

  1. 1
    Beninho85@email.null'

    Beninho85

    Updated version for Swift 3:

    @IBDesignable
    class FormTextField: UITextField {
    
        @IBInspectable var paddingLeft: CGFloat = 0
        @IBInspectable var paddingRight: CGFloat = 0
    
        override func textRect(forBounds bounds: CGRect) -> CGRect {
            return CGRect(x: bounds.origin.x + paddingLeft, y: bounds.origin.y, width: bounds.size.width - paddingLeft - paddingRight, height: bounds.size.height)
        }
    
        override func editingRect(forBounds bounds: CGRect) -> CGRect {
            return textRect(forBounds: bounds)
        }
    }
    
    Reply
  2. 2
    Hector

    Hector Ollison

    Here is a Swift code to give padding in UITextfield

     func txtPaddingVw(txt:UITextField) {
         let paddingView = UIView(frame: CGRectMake(0, 0, 10, 10))
         txt.leftViewMode = .Always
         txt.leftView = paddingView
     }
    

    and call using

    self.txtPaddingVw(txtPin)
    
    Reply
  3. 3
    Ben

    Ben Sullivan

    Swift 3 Solution

    class CustomTextField: UITextField {
    
     override func textRect(forBounds bounds: CGRect) -> CGRect {
      return CGRect(x: bounds.origin.x + 10, y: bounds.origin.y + 8, width: bounds.size.width - 20, height: bounds.size.height - 16)
     }
    
     override func editingRect(forBounds bounds: CGRect) -> CGRect {
      return self.textRect(forBounds: bounds)
     }
    }
    
    Reply
  4. 4
    rafalkitta@email.null'

    rafalkitta

    Nate Flink’s answer is my favourite, but don’t forget about right/left views.
    E.g for UITextField subclass:

    override func rightViewRectForBounds(bounds: CGRect) -> CGRect {
        let rightViewBounds = super.rightViewRectForBounds(bounds)
    
        return CGRectMake(CGRectGetMinX(rightViewBounds) - 10, CGRectGetMinY(rightViewBounds), CGRectGetWidth(rightViewBounds), CGRectGetHeight(rightViewBounds))
    }
    

    Above code set right padding for rightView of UITextField.

    Reply
  5. 5
    Phil@email.null'

    Phil

    Swift 2.0 Version:

    let paddingView: UIView = UIView(frame: CGRectMake(0, 0, 5, 20))
    textField.leftView = paddingView
    textField.leftViewMode = UITextFieldViewMode.Always;
    
    Reply
  6. 6
    bandejapaisa@email.null'

    bandejapaisa

    A Swift version for Xcode 6, where you can edit the inset value in Interface Builder / Storyboard.

    import UIKit
    
    @IBDesignable
    class FormTextField: UITextField {
    
        @IBInspectable var inset: CGFloat = 0
    
        override func textRectForBounds(bounds: CGRect) -> CGRect {
            return CGRectInset(bounds, inset, inset)
        }
    
        override func editingRectForBounds(bounds: CGRect) -> CGRect {
            return textRectForBounds(bounds)
        }
    
    }
    

    enter image description here

    Reply
  7. 7
    Saqib

    Saqib Saud

    textField.layer.borderWidth = 3;
    

    will add border, which worked as padding for me.

    Reply
  8. 8
    777Q@email.null'

    777Q

    1. Create a textfield Custom

    PaddingTextField.swift

    import UIKit
    class PaddingTextField: UITextField {
    
    @IBInspectable var paddingLeft: CGFloat = 0
    @IBInspectable var paddingRight: CGFloat = 0
    
    override func textRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectMake(bounds.origin.x + paddingLeft, bounds.origin.y,
            bounds.size.width - paddingLeft - paddingRight, bounds.size.height);
    }
    
    override func editingRectForBounds(bounds: CGRect) -> CGRect {
        return textRectForBounds(bounds)
    }}
    
    1. Set your textfield class is PaddingTextField and custom your padding as you want
      enter image description here
      enter image description here

    2. Enjoy it

    final

    Reply
  9. 9
    Brody

    Brody Robertson

    A good approach to add padding to UITextField is to subclass and add an edgeInsets property. You then set the edgeInsets and the UITextField will be drawn accordingly. This will also function correctly with a custom leftView or rightView set.

    OSTextField.h

    #import <UIKit/UIKit.h>
    
    @interface OSTextField : UITextField
    
    @property (nonatomic, assign) UIEdgeInsets edgeInsets;
    
    @end
    

    OSTextField.m

    #import "OSTextField.h"
    
    @implementation OSTextField
    
    - (id)initWithFrame:(CGRect)frame{
        self = [super initWithFrame:frame];
        if (self) {
            self.edgeInsets = UIEdgeInsetsZero;
        }
        return self;
    }
    
    -(id)initWithCoder:(NSCoder *)aDecoder{
        self = [super initWithCoder:aDecoder];
        if(self){
            self.edgeInsets = UIEdgeInsetsZero;
        }
        return self;
    }
    
    - (CGRect)textRectForBounds:(CGRect)bounds {
        return [super textRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets)];
    }
    
    - (CGRect)editingRectForBounds:(CGRect)bounds {
        return [super editingRectForBounds:UIEdgeInsetsInsetRect(bounds, self.edgeInsets)];
    }
    
    @end
    
    Reply
  10. 10
    DrPatience@email.null'

    DrPatience

    Here’s how to achieve this in SWIFT

    @IBOutlet weak var yourTextField: UITextField!
    
    override func viewDidLoad() {
    super.viewDidLoad()
    let paddingView = UIView(frame: CGRectMake(0, 0, 10, self.yourTextField.frame.height))
    yourTextField.leftView = paddingView
    yourTextField.leftViewMode = UITextFieldViewMode.Always
    }
    }
    

    Resource

    Reply
  11. 11
    Kirit

    Kirit Vaghela

    Objective C Code

    MyTextField.h

    #import <UIKit/UIKit.h>
    
    @interface MyTextField : UITextField
    
    @property (nonatomic) IBInspectable CGFloat padding;
    
    @end
    

    MyTextField.m

    #import "MyTextField.h"
    
    IB_DESIGNABLE
    @implementation MyTextField
    
    @synthesize padding;
    
    -(CGRect)textRectForBounds:(CGRect)bounds{
        return CGRectInset(bounds, padding, padding);
    }
    
    -(CGRect)editingRectForBounds:(CGRect)bounds{
        return [self textRectForBounds:bounds];
    }
    
    @end
    

    enter image description here

    Reply
  12. 12
    Anuj

    Anuj Kumar Rai

    The best way to do this is simply make a class using subclass of UITextField and in .m file

     #import "CustomTextField.h"
     #import <QuartzCore/QuartzCore.h>
     @implementation CustomTextField
    
    
    - (id)initWithCoder:(NSCoder*)coder 
     {
      self = [super initWithCoder:coder];
    
      if (self) {
    
    //self.clipsToBounds = YES;
    //[self setRightViewMode:UITextFieldViewModeUnlessEditing];
    
    self.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,15,46)];
    self.leftViewMode=UITextFieldViewModeAlways;
       }
    
      return self;
    
     }
    

    by doing this go to your storyboard or xib and click on identity inspector and replace UITextfield with your own “CustomTextField” in class option.

    Note: If you simply give padding with auto layout for textfield then your application will not run and show only blank screen.

    Reply
  13. 13
    King-Wizard@email.null'

    King-Wizard

    Just subclass UITextField like this (Swift version):

    import UIKit
    
    class CustomTextField: UITextField {
    
        override func textRectForBounds(bounds: CGRect) -> CGRect {
           return CGRectInset(bounds, 25.0, 0)
        }
    
        override func editingRectForBounds(bounds: CGRect) -> CGRect {
           return self.textRectForBounds(bounds)
        }
    
    }
    

    This adds horizontal padding of 25.0 points either side.

    Reply
  14. 14
    superarts.org@email.null'

    superarts.org

    Swift version:

    extension UITextField {
        @IBInspectable var padding_left: CGFloat {
            get {
                LF.log("WARNING no getter for UITextField.padding_left")
                return 0
            }
            set (f) {
                layer.sublayerTransform = CATransform3DMakeTranslation(f, 0, 0)
            }
        }
    }
    

    So that you can assign value in IB

    IBInspectable setting represented in Interface Builder

    Reply
  15. 15
    Inder

    Inder Kumar Rathore

    In iOS 6 myTextField.leftView = paddingView; is causing issue

    This solves the problem

    myTextField.layer.sublayerTransform = CATransform3DMakeTranslation(5, 0, 0);
    
    Reply
  16. 16
    Kasun

    Kasun Randika

    Based on @Evil Trout’s most voted answer I created a custom method in my VController class, like shown bellow:

    - (void) modifyTextField:(UITextField *)textField
    {
        UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
        textField.leftView = paddingView;
        textField.leftViewMode = UITextFieldViewModeAlways;
        textField.rightView = paddingView;
        textField.rightViewMode = UITextFieldViewModeAlways;
    
        [textField setBackgroundColor:[UIColor whiteColor]];
        [textField setTextColor:[UIColor blackColor]];
    }
    

    Now I can call that method inside (viewDidLoad method) and send any of my TextFields to that method and add padding for both right and left, and give text and background colors by writing just one line of code, as follows:

    [self modifyTextField:self.firstNameTxtFld];
    

    This Worked perfectly on iOS 7!
    I know that adding too much Views might make this a bit heavier class to be loaded. But when concerned about the difficulty in other solutions, I found myself more biased to this method and more flexible with using this way. 😉

    Thanks for the Hack “Evil Trout”! (bow)

    Reply
  17. 17
    Paulo

    Paulo Miguel Almeida

    Based on Evil Trout’s answer you might wanna create a category to make it easier to use across multiple applications.

    Header file:

    @interface UITextField (PaddingText)
    
    -(void) setLeftPadding:(int) paddingValue;
    
    -(void) setRightPadding:(int) paddingValue;
    @end
    

    Implementation file:

    #import "UITextField+PaddingText.h"
    
    @implementation UITextField (PaddingText)
    
    -(void) setLeftPadding:(int) paddingValue
    {
        UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, paddingValue, self.frame.size.height)];
        self.leftView = paddingView;
        self.leftViewMode = UITextFieldViewModeAlways;
    }
    
    -(void) setRightPadding:(int) paddingValue
    {
        UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, paddingValue, self.frame.size.height)];
        self.rightView = paddingView;
        self.rightViewMode = UITextFieldViewModeAlways;
    }
    
    @end
    

    Usage Example

    #import "UITextField+PaddingText.h"
    
    [self.YourTextField setLeftPadding:20.0f];
    

    Hope it helps you out guys

    Cheers

    Reply
  18. 18
    Mongi

    Mongi Zaidi

    The best solution I found so far is a category. That’s how I add a 5 points padding to left and right:

    @implementation UITextField (Padding)
    
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
    - (CGRect)textRectForBounds:(CGRect)bounds {
        return CGRectMake(bounds.origin.x + 5, bounds.origin.y,
                          bounds.size.width - 10, bounds.size.height);
    }
    - (CGRect)editingRectForBounds:(CGRect)bounds {
        return [self textRectForBounds:bounds];
    }
    #pragma clang diagnostic pop
    
    @end
    

    The #pragma’s are just for removing the annoying warnings

    Reply
  19. 19
    Lubakis@email.null'

    Lubakis

    Brody’s solution worked perfect for me. I have had to add side views on a textfield and add additional padding. So by implementing the custom UIEdgeInsets property to a UITextField subclass I have managed to achieve the task. I’m going to use this new subclass in all of my projects.

    Reply
  20. 20
    Kishor

    Kishor Kundan

    @Evil trout’s answer is great. I have been using this approach for quite a some time now. The only thing it lacks is “dealing with numerous text fields”. I tried other approaches but does not seem to work.

    Subclassing UITextField just to add a padding didn’t make any sense to me. So, I iterated over all UITextFields to add the padding.

    -(void) addPaddingToAllTextFields:(UIView*)view {
    
        for(id currentView in [view subviews]){
            if([currentView isKindOfClass:[UITextField class]]) {
                // Change value of CGRectMake to fit ur need
                [currentView setLeftView:[[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)]];
                [currentView setLeftViewMode:UITextFieldViewModeAlways];
            }
    
            if([currentView respondsToSelector:@selector(subviews)]){
                [textfieldarray addObjectsFromArray:[self addPaddingToAllTextFields:currentView]];
            }
        }
    }
    
    Reply
  21. 21
    Camsoft@email.null'

    Camsoft

    Just subclass UITextField like this:

    @implementation DFTextField
    
    
    - (CGRect)textRectForBounds:(CGRect)bounds
    {
        return CGRectInset(bounds, 10.0f, 0);
    }
    
    - (CGRect)editingRectForBounds:(CGRect)bounds
    {
        return [self textRectForBounds:bounds];
    }
    
    
    @end
    

    This adds horizontal padding of 10 points either side.

    Reply
  22. 22
    Towhidul

    Towhidul Islam

    Why not Attributed String !?!, this is one of the blessing feature of IOS 6.0 :)

    NSMutableParagraphStyle *mps = [[NSMutableParagraphStyle alloc] init];
                mps.firstLineHeadIndent = 5.0f;
    UIColor *placeColor = self.item.bgColor;
    
    textFieldInstance.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"My Place Holder" attributes:@{NSForegroundColorAttributeName: placeColor, NSFontAttributeName : [UIFont systemFontOfSize:7.0f], NSParagraphStyleAttributeName : mps}];
    
    Reply
  23. 23
    user1686700@email.null'

    user1686700

    Another consideration is that, if you have more than one UITextField where you are adding padding, is to create a separate UIView for each textfield – because they cannot be shared.

    Reply
  24. 24
    seenickcode@email.null'

    seenickcode

    I found it far easier to use a non-editable UITextView and set the contentOffset

    uiTextView.contentOffset = CGPointMake(8, 7);
    
    Reply
  25. 25
    Thomas

    Thomas Clayson

    You can’t set padding. Instead have a UIView which has your background image and the UITextField inside of it. Set the UITextField width as UIViewWidth-(paddingSize x 2) and the height similarly and then set it at point paddingSize,paddingSize.

    Reply
  26. 26
    Evil

    Evil Trout

    I found a neat little hack to set the left padding for this exact situation.

    Basically, you set the leftView property of the UITextField to be an empty view of the size of the padding you want:

    UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
    textField.leftView = paddingView;
    textField.leftViewMode = UITextFieldViewModeAlways;
    

    Worked like a charm for me!

    Reply
  27. 27
    woody121@email.null'

    woody121

    ^ these suggestions are great for those who are programmatically creating an interface.

    But there are two LAZY EASY WAYS for those of us who use the Xcode interface builder:

    • easier: put a UIImageView behind a text field

    • easiest: change the border style on your to the simple black square (second from left option), then add your image as a background image. The image takes precedence over the square, so you still get the padding needed for a normal image background, without the square actually being drawn on.

    EDIT: you can also use the black sphere (third from left option when selecting the UITextBox in IB), it does not work with the far right, “graphical sphere” style.

    Reply
  28. 28
    Stoto@email.null'

    Stoto

    I was based off Nate’s solution, but then i found it that this causes problems when you use the leftView/rightView properties, so its better tune the super’s implementation, because it will take the left/right view’s into account.

    - (CGRect)textRectForBounds:(CGRect)bounds {
        CGRect ret = [super textRectForBounds:bounds];
        ret.origin.x = ret.origin.x + 5;
        ret.size.width = ret.size.width - 10;
        return ret;
    }
    
    - (CGRect)editingRectForBounds:(CGRect)bounds {
        return [self textRectForBounds:bounds];
    }
    
    Reply
  29. 29
    Nate

    Nate Flink

    I created this category implementation and added it to the top of the .m file.

    @implementation UITextField (custom)
        - (CGRect)textRectForBounds:(CGRect)bounds {
            return CGRectMake(bounds.origin.x + 10, bounds.origin.y + 8,
                              bounds.size.width - 20, bounds.size.height - 16);
        }
        - (CGRect)editingRectForBounds:(CGRect)bounds {
            return [self textRectForBounds:bounds];
        }
    @end
    

    Based off the link Piotr Blasiak provided. It seemed simpler then creating a whole new subclass, and also simpler then adding the additional UIView. Still, it seems like something is missing to not be able to control the padding inside a text field.

    Swift 2 solution:

    import UIKit
    
    class CustomTextField: UITextField {
    
        required init?(coder aDecoder: NSCoder){
            super.init(coder: aDecoder)
        }
    
        override func textRectForBounds(bounds: CGRect) -> CGRect {
            return CGRectMake(bounds.origin.x + 10, bounds.origin.y + 8, bounds.size.width - 20, bounds.size.height - 16);
        }
    
        override func editingRectForBounds(bounds: CGRect) -> CGRect {
            return self.textRectForBounds(bounds);
        }
    }
    
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2017 SolutionMmyself.com