Add lefthand margin to UITextField
You can do it by extending UITextField
class and overriding two methods:
- (CGRect)textRectForBounds:(CGRect)bounds;- (CGRect)editingRectForBounds:(CGRect)bounds;
Here is the code:
The interface in MYTextField.h
@interface MYTextField : UITextField@end
Its implementation in MYTextField.m
@implementation MYTextFieldstatic CGFloat leftMargin = 28; - (CGRect)textRectForBounds:(CGRect)bounds{ bounds.origin.x += leftMargin; return bounds;} - (CGRect)editingRectForBounds:(CGRect)bounds{ bounds.origin.x += leftMargin; return bounds;}@end
As I have explained in a previous comment, the best solution in this case is to extend the UITextField
class instead of using a category, so you can use it explicitly on the desired text fields.
#import <UIKit/UIKit.h>@interface MYTextField : UITextField@end@implementation MYTextField- (CGRect)textRectForBounds:(CGRect)bounds { int margin = 10; CGRect inset = CGRectMake(bounds.origin.x + margin, bounds.origin.y, bounds.size.width - margin, bounds.size.height); return inset;}- (CGRect)editingRectForBounds:(CGRect)bounds { int margin = 10; CGRect inset = CGRectMake(bounds.origin.x + margin, bounds.origin.y, bounds.size.width - margin, bounds.size.height); return inset;}@end
A category is intended to add new functions to an existing class, not to override an existing method.
UITextField * textField = [[UITextField alloc]init];[textField setDelegate:self];[textField setFrame:CGRectMake(170,112,140,25)];[textField setBorderStyle:UITextBorderStyleNone];[textField setBackgroundColor:[UIColor clearColor]];[self.View addSubview:noofChildTField];UIView *paddingView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)] autorelease];textField.leftView = paddingView;textField.leftViewMode = UITextFieldViewModeAlways;
Try this code