UITextField 光标位置,placeholder样式
2017-03-20 本文已影响12630人
hehtao
一.Placeholder 样式更改
方法一:重写drawPlaceholderInRect:(CGRect)rect
方法
-(void)drawPlaceholderInRect:(CGRect)rect{
UIColor *placeholderColor = [UIColor dt_ColorWithString:@"#999999"];//设置颜色
[placeholderColor setFill];
CGRect placeholderRect = CGRectMake(rect.origin.x+5, (rect.size.height- self.font.pointSize)/2, rect.size.width, self.font.lineHeight );//设置Placeholder 位置.尺寸
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.lineBreakMode = NSLineBreakByTruncatingTail;
style.alignment = self.textAlignment;
NSDictionary *attr = [NSDictionary dictionaryWithObjectsAndKeys:style,NSParagraphStyleAttributeName, self.font, NSFontAttributeName, placeholderColor, NSForegroundColorAttributeName, nil];//设置Placeholder 样式
[self.placeholder drawInRect:placeholderRect withAttributes:attr];
}
方法二:通过KVC修改Placeholder颜色
UITextField *textField1 = [[UITextField alloc] init];
textField1.frame = CGRectMake(textFieldX, CGRectGetMaxY(textField.frame) + padding, viewWidth - 2 * textFieldX, textFieldH);
textField1.borderStyle = UITextBorderStyleRoundedRect;
textField1.placeholder = @"请输入占位文字";
textField1.font = [UIFont systemFontOfSize:14];
// "通过KVC修改占位文字的颜色"
[textField1 setValue:[UIColor greenColor] forKeyPath:@"_placeholderLabel.textColor"];
[self.view addSubview:textField1];
方法三: 修改attributedPlaceholder
属性
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"请输入占位文字" attributes:
@{NSForegroundColorAttributeName:[UIColor redColor],
NSFontAttributeName:textField.font
}];
textField.attributedPlaceholder = attrString;
二.控制placeHolder的位置
-(CGRect)placeholderRectForBounds:(CGRect)bounds
{
CGRect inset = CGRectMake(bounds.origin.x+100, bounds.origin.y, bounds.size.width -10, bounds.size.height);//更好理解些
return inset;
}
三. 修改文本展示区域,一般跟editingRectForBounds一起重写
- (CGRect)textRectForBounds:(CGRect)bounds
{
CGRect inset = CGRectMake(bounds.origin.x+10, bounds.origin.y, bounds.size.width-25, bounds.size.height);//更好理解些
return inset;
}
// 重写来编辑区域,可以改变光标起始位置,以及光标最右到什么地方,placeHolder的位置也会改变
-(CGRect)editingRectForBounds:(CGRect)bounds
{
CGRect inset = CGRectMake(bounds.origin.x+10, bounds.origin.y, bounds.size.width-25, bounds.size.height);//更好理解些
return inset;
}
四.UITextField 关于Rect的一些方法介绍
– textRectForBounds: //重写来重置文字区域
– drawTextInRect: //改变绘文字属性.重写时调用super可以按默认图形属性绘制,若自己完全重写绘制函数,就不用调用super了.
– placeholderRectForBounds: //重写来重置占位符区域
– drawPlaceholderInRect: //重写改变绘制占位符属性.重写时调用super可以按默认图形属性绘制,若自己完全重写绘制函数,就不用调用super了
– borderRectForBounds: //重写来重置边缘区域
– editingRectForBounds: //重写来重置编辑区域
– clearButtonRectForBounds: //重写来重置clearButton位置,改变size可能导致button的图片失真
– leftViewRectForBounds: // leftView 的位置
– rightViewRectForBounds: // rightView的位置