iOS开发技巧iOS小功能点

设置UITextField的placeholder的字体、颜色和

2017-04-11  本文已影响98人  伯牙呀
1、设置UITextField的placeholder的字体和颜色
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 50, 200, 50)];
textField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:textField];

// 方法一:KVC
textField.placeholder = @"this is placeholder";
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:18] forKeyPath:@"_placeholderLabel.font"];

// 方法二:属性字符串
field.attributedPlaceholder = [[NSAttributedString alloc]initWithString:@"this is placeholder" attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18], NSForegroundColorAttributeName:[UIColor redColor]}];
2、方法一引发的联想:

获取 placeholderLabel,然后对其进行属性设置。

UILabel *placeholderLabel = [textField valueForKey:@"_placeholderLabel"];
placeholderLabel.text = @"手机电话";
placeholderLabel.textColor = [UIColor redColor];
placeholderLabel.textAlignment = NSTextAlignmentCenter;
placeholderLabel.font = [UIFont boldSystemFontOfSize:18];
placeholderLabel.backgroundColor = [UIColor cyanColor];

注意:可能部分属性设置不生效。

3、textField.fontplaceholderLabel.font 大小不同引发的偏移:
修改前的偏移 修改后的效果

解决偏移方法:

// 返回placeholderLabel的bounds,改变返回值,是调整placeholderLabel的位置
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
    return CGRectMake(0, 0 , self.bounds.size.width, self.bounds.size.height);
}
// 这个函数是调整placeholder在placeholderLabel中绘制的位置以及范围
// 参数 offSetY 是绘制placeholderLabel 时向下偏移的大小
- (void)drawPlaceholderInRect:(CGRect)rect {
    [super drawPlaceholderInRect:CGRectMake(0, offSetY , self.bounds.size.width, self.bounds.size.height)];
}
4、使 UITextField 的文本(光标)的位置向右缩进

在我们使用原生 UITextField 的时候,placeholder 和输入的文字都是紧挨着 UITextField 的边缘的。

// 未输入时文本的位置,向右缩进10
- (CGRect)textRectForBounds:(CGRect)bounds {
    return CGRectInset(bounds, 10, 0);
}
// 输入后文本的位置,向右缩进10
- (CGRect)editingRectForBounds:(CGRect)bounds {
    return CGRectInset(bounds, 10, 0);
}
上一篇下一篇

猜你喜欢

热点阅读