今天在适配iOS13的时候发现像获取或设置UITextField的PlaceHolder崩溃,造成崩溃的原因是如下这样的写法,现在被系统禁止使用了
color = [textField valueForKeyPath:@"_placeholderLabel.textColor"];
现在正确的写法如下
UITextField *textField = [[UITextField alloc] init];
textField.placeholder = @" ";
Ivar ivar = class_getInstanceVariable([UITextField class], "_placeholderLabel");
UILabel *placehoderLabel = object_getIvar(textField, ivar);
color = placehoderLabel.textColor;
通过运行时来获取系统是允许这样做的,亲测可用。
以上是Objc版本,现在我们看一下swift如何写
let iVar = class_getInstanceVariable(UITextField.self, "_placeholderLabel")!
let placeholderLabel = object_getIvar(textField, iVar) as! UILabel
color = placeholderLabel.textColor