iOS 13 修改私有属性“_placeholderLabel”

2019-10-08  本文已影响0人  Tang杰

iOS13 使用以下两个方法出现crash

- (void)setValue:(nullable id)value forKeyPath:(NSString *)keyPath
 - (nullable id)valueForKeyPath:(NSString *)keyPath

以UITextField为例解决思路如下:

#import <objc/runtime.h>

- (void)updatePlaceholderColor {
 Ivar ivar = class_getInstanceVariable([textField class], "_placeholderLabel");
 id placeholderLabel = object_getIvar(textField, ivar);
 
 Ivar ivar_1 = class_getInstanceVariable([placeholderLabel class], "_defaultAttributes");
 NSMutableDictionary *defaultTextAttributes = object_getIvar(placeholderLabel, ivar_1);
 [defaultTextAttributes setObject:UIColor.redColor forKey:@"NSColor"];
 // 或者以下一句
 // [placeholderLabel performSelector:@selector(setTextColor:) withObject:UIColor.redColor];
}

注:对应的关键字可以通过runtime打印,也可以xcode断点调试查看

上一篇 下一篇

猜你喜欢

热点阅读