美文网首页
利用runtime修改系统控件(textField、textVi

利用runtime修改系统控件(textField、textVi

作者: 十一遥 | 来源:发表于2019-01-23 16:20 被阅读13次
利用runtime个修改textField的占位文字颜色,给textView添加占位文本
效果如下

系统方法修改占位文字颜色

//textField
self.textF.placeholder = @"请输入用户名";

NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSForegroundColorAttributeName] = [UIColor redColor];

self.textF.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"请输入用户名" attributes:attrs];
#import <objc/runtime.h> //引入runtime库
    // 成员变量的数量
        unsigned int count;
        Ivar *ivars = class_copyIvarList([UITextField class], &count);
        for (int i = 0; i < count; i++) {
            // 取出i位置的成员变量
            Ivar ivar = ivars[I];
            NSLog(@"成员变量%s", ivar_getName(ivar));
        }
        free(ivars);

这里会打印所有成员变量处理,搜placeholder

利用runtime查看textField成员变量


从_placeholderLabel可以大致猜测placehoder是个label

   NSLog(@"---%@",[self.textF valueForKey:@"_placeholderLabel"]);
   self.textF.placeholder = @"请输入用户名";
   [self.textF setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
   NSLog(@"---%@",[self.textF valueForKey:@"_placeholderLabel"]);

上面做效果就实现了,我打印了日志如下,可以看出来在没有调placeholder时_placeholderLabel时空的,在调用之后,它是有值的,所以推测textField的_placeholderLabel是懒加载的,调用时创建。


WX20190123-155414.png

下面用同样方法查看textView成员变量

    // 成员变量的数量
        unsigned int count;
        Ivar *ivars = class_copyIvarList([UITextView class], &count);
        for (int i = 0; i < count; i++) {
            // 取出i位置的成员变量
            Ivar ivar = ivars[I];
            NSLog(@"成员变量%s", ivar_getName(ivar));
        }
        free(ivars);

打印结果:


从上图可以看到textView也有_placeholderLabel成员变量

    NSLog(@"---%@",[self.textV valueForKey:@"_placeholderLabel"]);
    [self.textV setValue:@"请输入用户名" forKeyPath:@"_placeholderLabel.text"];
    NSLog(@"---%@",[self.textV valueForKey:@"_placeholderLabel"]);

照猫画虎,用下面代码发现并未奏效,且前后答应皆为null,于是我猜测,要么KVC的键名不对(不对也没办法,谁能猜得到呢?),要么是它只有_placeholderLabel成员变量,压根没有实现。
赌第二条路,自己实现,KVC给它设置进去

    UILabel *placeHolderLabel = [[UILabel alloc] init];
    placeHolderLabel.text = @"请输入评价";
    placeHolderLabel.numberOfLines = 0;
    placeHolderLabel.textColor = [UIColor orangeColor];
    [placeHolderLabel sizeToFit];
    
    if (self.textV.text.length == 0) {
        [self.textV addSubview:placeHolderLabel];//这句很重要不要忘了
    }
    
    [self.textV setValue:placeHolderLabel forKey:@"_placeholderLabel"];
//这是可以成功的

相关文章

网友评论

      本文标题:利用runtime修改系统控件(textField、textVi

      本文链接:https://www.haomeiwen.com/subject/ogzjjqtx.html