自定义UITextField
创建一个类,继承于UITextField.
1.控制清除按钮位置
-(CGRect)clearButtonRectForBounds:(CGRect)bounds
{
// bounds为textFiled的bounds
return CGRectMake(bounds.origin.x + bounds.size.width - 50, bounds.origin.y + bounds.size.height -20, 16, 16);
}
2.控制placeHolder的位置
-(CGRect)placeholderRectForBounds:(CGRect)bounds
{
CGRect inset = CGRectMake(bounds.origin.x+100, bounds.origin.y, bounds.size.width -10, bounds.size.height);//更好理解些
return inset;
}
3.//控制placeHolder的颜色、字体
- (void)drawPlaceholderInRect:(CGRect)rect
{
NSMutableDictionary *attribute = [NSMutableDictionary new];
// 设置字体大小
[attribute setObject:[UIFont systemFontOfSize:14] forKey:NSFontAttributeName];
// 设置颜色
[attribute setObject:[UIColor redColor] forKey:NSForegroundColorAttributeName];
[self.placeholder drawWithRect:rect options:NSStringDrawingUsesLineFragmentOrigin attributes:attribute} context:nil];
}
4.控制显示文本的位置
-(CGRect)textRectForBounds:(CGRect)bounds
{
//return CGRectInset(bounds, 50, 0);
CGRect inset = CGRectMake(bounds.origin.x+190, bounds.origin.y, bounds.size.width -10, bounds.size.height);
return inset;
}
5.控制编辑文本的位置
-(CGRect)editingRectForBounds:(CGRect)bounds
{
//return CGRectInset( bounds, 10 , 0 );
CGRect inset = CGRectMake(bounds.origin.x +10, bounds.origin.y, bounds.size.width -10, bounds.size.height);
return inset;
}
6.控制左视图位置
- (CGRect)leftViewRectForBounds:(CGRect)bounds
{
CGRect inset = CGRectMake(bounds.origin.x +10, bounds.origin.y, bounds.size.width-250, bounds.size.height);
return inset;
//return CGRectInset(bounds,50,0);
}
7.自定义placeholder
UITextField *testFiled = [[UITextField alloc] init];
[self.view addSubview:testFiled];
NSString *placeholderText = @"这是个测试";
NSMutableAttributedString *MPlaceholderStr = [[NSMutableAttributedString alloc] initWithString:placeholderText];
[MPlaceholderStr addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} range:NSMakeRange(0, placeholderText.length)];
testFiled.attributedPlaceholder = MPlaceholderStr;
tips: 如果单独设置了placeholder字体大小,placeholder位置会产生偏移,将textField.font 设置为相同就回归正常.
- 注:其它设置与自定义UILabel.text同理。
网友评论