简体   繁体   中英

Add padding to uitextfield using appearance

I don't want to subclass the UITextField class just to get text padding.

I want to do it using the appearance proxy.

I tried this:

UIView *padding = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 5, 2)];
[[UITextField appearance] setLeftView:padding];
[[UITextField appearance] setLeftViewMode:UITextFieldViewModeAlways];

unfortunately, if i put this code in my app delegate, any view controller that has a uitextfield in it, fails to load the view

how can I add padding to the textfield without subclassing it ?

Can you try these..

- (CGRect)textRectForBounds:(CGRect)bounds {
    int margin = 10;
    CGRect inset = CGRectMake(bounds.origin.x + bounds.size.width/2, bounds.origin.y, bounds.size.width/2 - margin, bounds.size.height);
    return inset;
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    int margin = 10;
    CGRect inset = CGRectMake(bounds.origin.x + bounds.size.width/2, bounds.origin.y, bounds.size.width/2 - margin, bounds.size.height);
    return inset;
}

(Or)

do like this

// Do any additional setup after loading the view from its nib.

 UIView *paddingTxtfieldView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 42)];// what ever you want 
 txtfield.leftView = paddingTxtfieldView;
 txtfield.leftViewMode = UITextFieldViewModeAlways;
 txtfield.returnKeyType = UIReturnKeyNext;// if you want to go next textfiled write this otherwise "UIReturnKeyDone"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM