0

I want to add blank space in the beginning of my UITextField. I am subclassing my UITextfield with the following code. I am not sure what is going wrong here

- (CGRect)textRectForBounds:(CGRect)bounds {
return CGRectMake(bounds.origin.x + 15, bounds.origin.y + 15, bounds.size.width, bounds.size.height);
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
return CGRectMake(bounds.origin.x + 15, bounds.origin.y + 15, bounds.size.width, bounds.size.height);
}

Thanks in Advance

AJ Sanjay
  • 1,276
  • 1
  • 12
  • 29

2 Answers2

1

Try this

UILabel * leftView = [[UILabel alloc] initWithFrame:CGRectMake(10,0,7,26)];
leftView.backgroundColor = [UIColor clearColor];


textField.leftView = leftView;

textField.leftViewMode = UITextFieldViewModeAlways;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

How to add space at start of UITextField

Community
  • 1
  • 1
0

You should override textRectForBounds and editingRectForBounds like this:

CustomTextField.h:

#import <UIKit/UIKit.h>

@interface CustomTextField : UITextField

@property CGFloat inset;

@end

CustomTextField.m:

#import "CustomTextField.h"

@implementation CustomTextField

- (CGRect)textRectForBounds:(CGRect)bounds {

    CGRect rect = CGRectInset(bounds, _inset, 0);
    return rect;
}


- (CGRect)editingRectForBounds:(CGRect)bounds {

    CGRect rect = CGRectInset(bounds, _inset, 0);
    return rect;
}

@end

ViewController.m:

#import "ViewController.h"
#import "CustomTextField.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet CustomTextField *textField;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    _textField.inset = 20;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

The result:

aircraft
  • 25,146
  • 28
  • 91
  • 166