利用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"];
//這是可以成功的