@property(nullable, nonatomic,copy) NSAttributedString*attributedPlaceholder NS_AVAILABLE_IOS(6_0); // default is nil2、重写drawPlaceholderInRect方法
- (void)drawPlaceholderInRect:(CGRect)rect;3、修改UITextField内部placeholderLaber的颜色
[textField setValue:[UIColor grayColor] forKeyPath@"placeholderLaber.textColor"];以下是详细的实现过程
placeholder
的文字颜色。
使用前
使用后
使用attributedPlaceholder
自定义GYLLoginRegisterTextField
类,继承自UITextField;实现awakeFromNib()
方法,如果使用storyboard
,那么修改对应的UITextField的CustomClass
为GYLLoginRegisterTextField
即可
具体代码如下:
#import "GYLLoginRegisterTextField.h"@implementation GYLLoginRegisterTextField- (void)awakeFromNib{ self.tintColor = [UIColor whiteColor];//设置光标颜色 //修改占位符文字颜色 NSMutableDictionary *attrs = [NSMutableDictionary dictionary]; attrs[NSForegroundColorAttributeName] = [UIColor whiteColor]; self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:attrs];}@end重写drawPlaceholderInRect方法
GYLLoginRegisterTextField
,继承自UITextField,重写drawPlaceholderInRect
方法,后续相同#import "GYLLoginRegisterTextField.h"@implementation GYLLoginRegisterTextField- (void)awakeFromNib{ self.tintColor = [UIColor whiteColor];//设置光标颜色}- (void)drawPlaceholderInRect:(CGRect)rect{ NSMutableDictionary *attrs = [NSMutableDictionary dictionary]; attrs[NSForegroundColorAttributeName] = [UIColor whiteColor]; attrs[NSFontAttributeName] = self.font; //画出占位符 CGRect placeholderRect; placeholderRect.size.width = rect.size.width; placeholderRect.size.height = rect.size.height; placeholderRect.origin.x = 0; placeholderRect.origin.y = (rect.size.height - self.font.lineHeight) * 0.5; [self.placeholder drawInRect:placeholderRect withAttributes:attrs]; //或者 /* CGPoint placeholderPoint = CGPointMake(0, (rect.size.height - self.font.lineHeight) * 0.5); [self.placeholder drawAtPoint:placeholderPoint withAttributes:attrs]; */}@end修改UITextField内部placeholderLaber的颜色
placeholderLaber.textColor
#import "GYLLoginRegisterTextField.h"@implementation GYLLoginRegisterTextField- (void)awakeFromNib{ self.tintColor = [UIColor whiteColor];//设置光标颜色 //修改占位符文字颜色 [self setValue:[UIColor grayColor] forKeyPath@"placeholderLaber.textColor"];}@end第三种方法比较简单,建议可以将此封装:扩展UITextField,新建category,添加
placeholderColor
属性,使用KVC重写set
和get
方法。