iOS-改变UITextField的Placeholder颜色的三种方式
2017-03-22 15:05
417 查看
CGFloat viewWidth = self.view.bounds.size.width; CGFloat textFieldX = 50; CGFloat textFieldH = 30; CGFloat padding = 30; UITextField *textField = [[UITextField alloc] init]; textField.frame = CGRectMake(textFieldX, 100, viewWidth - 2 * textFieldX, textFieldH); textField.borderStyle = UITextBorderStyleRoundedRect; // 边框类型 textField.font = [UIFont systemFontOfSize:14]; // 就下面这两行是重点 NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"请输入占位文字" attributes: @{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:textField.font }];
textField.attributedPlaceholder = attrString;
[self.view addSubview:textField];
方法二:通过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];
方法三:通过重写UITextField的drawPlaceholderInRect:方法修改Placeholder颜色
1、自定义一个TextField继承自UITextField
2、重写drawPlaceholderInRect:方法
3、在drawPlaceholderInRect方法中设置placeholder的属性
// 重写此方法 -(void)drawPlaceholderInRect:(CGRect)rect { // 计算占位文字的 Size CGSize placeholderSize = [self.placeholder sizeWithAttributes: @{NSFontAttributeName : self.font}]; [self.placeholder drawInRect:CGRectMake(0, (rect.size.height - placeholderSize.height)/2, rect.size.width, rect.size.height) withAttributes: @{NSForegroundColorAttributeName : [UIColor blueColor], NSFontAttributeName : self.font}];
}
1、当我们使用纯代码创建UITextField时,用第二种方法(KVC)修改占位文字颜色是最便捷的 。
2、当我们使用XIB或者Storyboard创建UITextField时,通过自定义UITextField,修改占位文字颜色是最适合的。
3、我们也可以在第三种重写方法中,通过结合第二种方法中的KVC修改属性来实现。
相关文章推荐
- iOS-改变UITextField的Placeholder颜色的三种方式
- iOS-改变UITextField的Placeholder颜色的三种方式
- iOS改变UITextField占位文字颜色的三种方法
- iOS-改变UITextField的占位文字颜色(三种)
- iOS-改变UITextField(纯代码 /xib) 中的Placeholder颜色的几种方法
- iOS 改变UITextField中光标颜色
- iOS 改变UITextField中光标颜色
- iOS改变UITextField中光标颜色
- iOS利用storyboard修改UITextField的placeholder文字颜色
- IOS 改变提示placeholder颜色和大小
- iOS利用storyboard修改UITextField的placeholder文字颜色
- //改变UITextfield的Placeholder字体的颜色
- UITextField/UITextView 选中时改变边框颜色及UITextView的Placeholder
- [IOS]UITextField修改placeholder颜色
- iOS TextField改变placeholder颜色的方法
- iOS-UITextField中给placeholder动态设置颜色的四种方法
- iOS 修改UITextField的placeholder属性的字体颜色(修改UITextField占位符字体的颜色)
- iOS UITextField更改placeholder颜色
- iOS修改UITextField的提示语(placeholder)的字体大小和颜色
- iOS:改变UITextField或UITextView的光标颜色