Text insertion for UITextField?

I want to insert the text of a UITextField.

Is that possible?

#1 building

Using textRectForBounds: is the correct method. I wrap it in subclasses, so you can simply use textEdgeInsets. See also SSTextField .

#2 building

I can do this in the following ways:

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

Of course, remember to import quartz core and add the framework to your project.

#3 building

If you only need the left margin, you can try the following:

UItextField *textField = [[UITextField alloc] initWithFrame:...];
UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, textField.frame.size.height)];
leftView.backgroundColor = textField.backgroundColor;
textField.leftView = leftView;
textField.leftViewMode = UITextFieldViewModeAlways;

It works for me. I hope it will help you.

#4 building

If you only want to change the TOP and LEFT indents, then

//Placeholder location

- (CGRect)textRectForBounds:(CGRect)bounds {

CGRect frame = bounds;
frame.origin.y = 3;
 frame.origin.x = 5;
bounds = frame;
return CGRectInset( bounds , 0 , 0 );
}

//Text position

- (CGRect)editingRectForBounds:(CGRect)bounds {

CGRect frame = bounds;
frame.origin.y = 3;
 frame.origin.x = 5;
bounds = frame;
return CGRectInset( bounds , 0 , 0 );
}

#5 building

A good way to add padding to a UITextField is to subclass the UITextField and add the edgeInsets property. Then, you set edgeInsets and draw UITextField accordingly. Using a custom leftView or rightView set also works.

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

Posted on Fri, 07 Feb 2020 11:37:13 -0500 by gabrielserban