利用runtime個(gè)修改textField的占位文字顏色翠储,給textView添加占位文本
效果如下
系統(tǒng)方法修改占位文字顏色
//textField
self.textF.placeholder = @"請(qǐng)輸入用戶名";
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSForegroundColorAttributeName] = [UIColor redColor];
self.textF.attributedPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"請(qǐng)輸入用戶名" attributes:attrs];
#import <objc/runtime.h> //引入runtime庫
// 成員變量的數(shù)量
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);
這里會(huì)打印所有成員變量處理筐乳,搜placeholder
利用runtime查看textField成員變量
從_placeholderLabel可以大致猜測(cè)placehoder是個(gè)label
NSLog(@"---%@",[self.textF valueForKey:@"_placeholderLabel"]);
self.textF.placeholder = @"請(qǐng)輸入用戶名";
[self.textF setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
NSLog(@"---%@",[self.textF valueForKey:@"_placeholderLabel"]);
上面做效果就實(shí)現(xiàn)了隘马,我打印了日志如下,可以看出來在沒有調(diào)placeholder時(shí)_placeholderLabel時(shí)空的扫步,在調(diào)用之后,它是有值的匈子,所以推測(cè)textField的_placeholderLabel是懶加載的河胎,調(diào)用時(shí)創(chuàng)建。
WX20190123-155414.png
下面用同樣方法查看textView成員變量
// 成員變量的數(shù)量
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);
打印結(jié)果:
從上圖可以看到textView也有_placeholderLabel成員變量
NSLog(@"---%@",[self.textV valueForKey:@"_placeholderLabel"]);
[self.textV setValue:@"請(qǐng)輸入用戶名" forKeyPath:@"_placeholderLabel.text"];
NSLog(@"---%@",[self.textV valueForKey:@"_placeholderLabel"]);
照貓畫虎虎敦,用下面代碼發(fā)現(xiàn)并未奏效游岳,且前后答應(yīng)皆為null,于是我猜測(cè)其徙,要么KVC的鍵名不對(duì)(不對(duì)也沒辦法胚迫,誰能猜得到呢?)唾那,要么是它只有_placeholderLabel成員變量访锻,壓根沒有實(shí)現(xiàn)。
賭第二條路,自己實(shí)現(xiàn)期犬,KVC給它設(shè)置進(jìn)去
UILabel *placeHolderLabel = [[UILabel alloc] init];
placeHolderLabel.text = @"請(qǐng)輸入評(píng)價(jià)";
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"];
//這是可以成功的