简体   繁体   中英

How to give padding to UITextField in iOS?

I want to give padding from left into the textfield.I have added a background image to textfield due to which text in textfield always start from very left edge.I have tried below solution but that does not work for too many text fields.

    UIView *fieldEmail = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
    self.txt_fname.leftViewMode = UITextFieldViewModeAlways;
    self.txt_fname.leftView     = fieldEmail;

Please suggest me some simple solutin in which i don't have to create a seprate view for giving the padding.

The answer accepted in the question does not work for me. Set padding for UITextField with UITextBorderStyleNone

You can create a Category of UITextFiled like following code:

.H class

#import <UIKit/UIKit.h>

@interface UITextField (Textpadding)


-(CGRect)textRectForBounds:(CGRect)bounds;
-(CGRect)editingRectForBounds:(CGRect)bounds;
@end

.M class

#import "UITextField+Textpadding.h"

@implementation UITextField (Textpadding)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
-(CGRect)textRectForBounds:(CGRect)bounds {



    return CGRectMake(bounds.origin.x+20 , bounds.origin.y ,
                      bounds.size.width , bounds.size.height-2 );
}
-(CGRect)editingRectForBounds:(CGRect)bounds {
    return [self textRectForBounds:bounds];
}

This category will setting your all text-filed padding by default at run time.

How to create Category

  • Press cmd+n for new class create and select Objective-c class.

在此输入图像描述

  • Then select Category like following.

在此输入图像描述

  • Set Class name.

在此输入图像描述

  • Set file name.

在此输入图像描述

That's it now do code in this class as my answer.

Another easier and quicker solution can be that you make an imageview and add image for textfield in that. Then add the real text field on top of imageview, and move it as required, for instance as you want left padding, you can move text field a little away from imageview's x-cordinate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM