iOS13 禁止textfield通过KVC获取和修改私有属性

  • UITextField

在ios 13之前,UITextField可以通过KVC修改属性


//字体颜色

[textField setValue:[UIColor whiteColor]forKeyPath:@"_placeholderLabel.textColor"];

//字体大小

[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"]; 

//水平居中

[textField setValue:[NSNumber numberWithInteger:NSTextAlignmentCenter] forKeyPath:@"_placeholderLabel.textAlignment"];



在ios 13之后,UITextField禁止通过KVC修改属性,以下提供两种方式

解决方式1:通过attributedPlaceholder属性修改Placeholder颜色



NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"请输入占位文字" attributes: @{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:textField.font }];

textField.attributedPlaceholder = attrString;


解决方式2:为UITextField重新写一个方法



- (void)resetTextField:(UITextField *)textField{
 	Ivar ivar =  class_getInstanceVariable([textField class], "_placeholderLabel");

    UILabel *placeholderLabel = object_getIvar(textField, ivar);

    placeholderLabel.text = title;

    placeholderLabel.textColor = color;

    placeholderLabel.font = [UIFont systemFontOfSize:fontSize];

    placeholderLabel.textAlignment = alignment;
}


发布了17 篇原创文章 · 获赞 15 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Harvey_DHui/article/details/105167550
今日推荐