APP中经常用到UITextField,placeholder和text都是从最左边开始,看起来很不美观。想要在文本之前添加一个起始空格。
方法:
重写UITextFiled的两个方法,生成一个子类:
#import "HeaderEmptyTextField.h"
@implementation HeaderEmptyTextField
- (CGRect)textRectForBounds:(CGRect)bounds{
return CGRectInset(bounds, 15, 0);
}
- (CGRect)editingRectForBounds:(CGRect)bounds{
return CGRectInset(bounds, 15, 0);
}
@end
这时,在创建UITextFiled的代码中加一个参数
- (UITextField *)createTextFieldWithFrame:(CGRect)textFieldFrame Font:(CGFloat)font textColor:(UIColor *)textColor Placeholder:(NSString *)placeholder headerEmpty:(BOOL)isEmpty
{
if (isEmpty) {
HeaderEmptyTextField *textField = [[HeaderEmptyTextField alloc]initWithFrame:textFieldFrame];
textField.textColor = textColor;
textField.font = [UIFont systemFontOfSize:font];
textField.borderStyle = UITextBorderStyleNone;
textField.placeholder = placeholder;
return textField;
}else{
UITextField *textField = [[UITextField alloc]initWithFrame:textFieldFrame];
textField.textColor = textColor;
textField.font = [UIFont systemFontOfSize:font];
textField.borderStyle = UITextBorderStyleNone;
textField.placeholder = placeholder;
return textField;
}
}
这样,在外部直接传一个BOOL值,需要前面加空格的时候传YES,否则传NO,外部不需要知道是用HeaderEmptyTextField还是用UITextField,统一用UITextField,因为UITextField是父类。