Indent the text in a UITextField

后端 未结 8 1318
日久生厌
日久生厌 2020-12-07 08:35

My question is as simple as the title, but here\'s a little more:

I have a UITextField, on which I\'ve set the background image. The problem is that the text hugs so

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 09:09

    A good approach to add padding to UITextField is to subclass UITextField , overriding the rectangle methods and adding an edgeInsets property. You can 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 
    
    @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 = UIEdgeInsetsMake(0, 0, 0, 0);
        }
        return self;
    }
    
    -(id)initWithCoder:(NSCoder *)aDecoder{
        self = [super initWithCoder:aDecoder];
        if(self){
            self.edgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        }
        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
    

提交回复
热议问题