IOS UITextfield占字符颜色

处理文本占字符颜色

越复杂的东西越要封装,
当我们的额设置的东西只要一次的时候,而且使用的xib我们可以在aweakFromNib中设置,
当我们找这个占字符的先去头文件查找,attributePlaceholderString

NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[NSForegroundColorAttributeName] = [UIColor whiteColor];
    
    self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:dic];

快速设置占字符颜色

屏幕快照 2019-10-22 上午11.07.31.png

这是看可以看懂field的内部,这是我们可以通过kvc进行设置。但是需要知道属性名字,首先,要获取属性名,1可以通过runtime来打印,2,可以用断点,用断点我们可以查看到

屏幕快照 2019-10-22 上午11.17.50.png
屏幕快照 2019-10-22 上午11.18.21.png

他有一个placeholderLabel的属性
这时候我们就可以利用KVC进行设置

UILabel *placeholderLabel = [self valueForKey:@"placeholderLabel"];
    placeholderLabel.textColor = [UIColor whiteColor];

如果我们想以后都使用可以自定义一个分类

.h
@property UIColor *placeholderColor;

.m
- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
    UILabel *placeholderLabel = [self valueForKey:@"placeholderLabel"];
    placeholderLabel.textColor = placeholderColor;
}
- (UIColor *)placeholderColor
{
    return nil;
}

runtime设置

使用上面的设置方式,要特别注意设置的顺序需要先设置占位文字,在设置颜色,因为这个label是懒加载,如果我们没有设置文字的话,就为nil这时候我们设置颜色是没有效果的。所以我门完善一下。使用runtime。修改placeholder的set方法,和我们自己的设置的方法交换实现.

+ (void)load
{
    // setPlaceholder
    Method setPlaceholderMethod = class_getInstanceMethod(self, @selector(setPlaceholder:));
    Method setXmg_PlaceholderMethod = class_getInstanceMethod(self, @selector(setXmg_Placeholder:));
    
    method_exchangeImplementations(setPlaceholderMethod, setXmg_PlaceholderMethod);
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
    
    // 给成员属性赋值 runtime给系统的类添加成员属性
    // 添加成员属性
    objc_setAssociatedObject(self, @"placeholderColor", placeholderColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    // 获取占位文字label控件
    UILabel *placeholderLabel = [self valueForKey:@"placeholderLabel"];
    
    // 设置占位文字颜色
    placeholderLabel.textColor = placeholderColor;
    
}


- (UIColor *)placeholderColor
{
    return objc_getAssociatedObject(self, @"placeholderColor");
}

// 设置占位文字
// 设置占位文字颜色
- (void)setXmg_Placeholder:(NSString *)placeholder
{
    [self setXmg_Placeholder:placeholder];
    
    self.placeholderColor = self.placeholderColor;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值