1.基础办法:(在扩展中使用KVC获取属性的值)(先设置文本颜色,后设置placeholder, placeholder颜色无效)
NS_ASSUME_NONNULL_BEGIN @interface UITextField (Placeholder) @property UIColor *placeholderColor; @end NS_ASSUME_NONNULL_END #import "UITextField+Placeholder.h" #import <objc/message.h> // 设置占位文字颜色 //_textField.placeholderColor = [UIColor greenColor]; // 设置占位文字:每次设置占位文字的后,在拿到之前保存占位文字颜色,重新设置 // [_textField setHk_Placeholder:@"123"]; @implementation UITextField (Placeholder) - (void)setPlaceholderColor:(UIColor *)placeholderColor { // 设置占位文字颜色 UILabel *placeholderLabel = [self valueForKey:@"placeholderLabel"]; placeholderLabel.textColor = placeholderColor; } - (UIColor *)placeholderColor { return nil; } @end // 基础方法 //设置占位文字:每次设置占位文字的后,在拿到之前保存占位文字颜色,重新设置 // 分析:为什么先设置占位文字颜色,就没有效果 => 占位文字label拿不到
2.使用Runtime实现
NS_ASSUME_NONNULL_BEGIN @interface UITextField (Placeholder) @property UIColor *placeholderColor; @end NS_ASSUME_NONNULL_END #import "UITextField+Placeholder.h" #import <objc/message.h> // 设置占位文字颜色 //_textField.placeholderColor = [UIColor greenColor]; // 设置占位文字:每次设置占位文字的后,在拿到之前保存占位文字颜色,重新设置 // [_textField setHk_Placeholder:@"123"]; @implementation UITextField (Placeholder) + (void)load { // setPlaceholder Method setPlaceholderMethod = class_getInstanceMethod(self, @selector(setPlaceholder:)); Method setHk_PlaceholderMethod = class_getInstanceMethod(self, @selector(setHk_Placeholder:)); method_exchangeImplementations(setPlaceholderMethod, setHk_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)setHk_Placeholder:(NSString *)placeholder { [self setHk_Placeholder:placeholder]; self.placeholderColor = self.placeholderColor; } @end