//通过runtime,我们发现UITextField有一个叫做_placeholderLabel的私有变量,下面来看下:
unsignedintcount =0;
Ivar*ivars =class_copyIvarList([UITextFieldclass], &count);
NSLog(@"count%d",count);
for(inti =0; i < count; i++) {
Ivarivar = ivars[i];
constchar*name =ivar_getName(ivar);
NSString*objcName = [NSStringstringWithUTF8String:name];
NSLog(@"%d : %@",i,objcName);
}
通过上面的代码已经证实确实有_placeholderLabel,这个私有变量,现在我们可以通过KVC来访问是有变量,并设置placeholder的颜色、字体等属性
UITextField*textField = [[UITextFieldalloc]initWithFrame:CGRectMake(0,100, [UIScreenmainScreen].bounds.size.width,30)];
[textFieldsetBackgroundColor:[UIColorgrayColor]];
[self.viewaddSubview:textField];
//_placeholderLabel
UILabel*placeHolderLabel = [[UILabelalloc]init];
placeHolderLabel.text=@"请输入文字";
placeHolderLabel.numberOfLines=0;
placeHolderLabel.textColor= [UIColorredColor];
[placeHolderLabelsizeToFit];
[textFieldaddSubview:placeHolderLabel];
// 字体保持一致
textField.font= [UIFontsystemFontOfSize:13.f];
placeHolderLabel.font= [UIFontsystemFontOfSize:13.f];
[textFieldsetValue:placeHolderLabelforKey:@"_placeholderLabel"];
}