Indent the text in a UITextField

后端 未结 8 1300
日久生厌
日久生厌 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 <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 = 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
    
    0 讨论(0)
  • 2020-12-07 09:18

    If you don't want to create @IBOutlet's could simply subclass (answer in Swift):

    class PaddedTextField: UITextField {
    
      override func awakeFromNib() {
          super.awakeFromNib()
    
          let spacerView = UIView(frame:CGRect(x: 0, y: 0, width: 10, height: 10))
          leftViewMode = .always
          leftView = spacerView
       }
    }
    
    0 讨论(0)
提交回复
热议问题