但是,UITextField中有一个placeholder属性,可以设置UITextField的占位文字,起到提示用户输入相关信息的作用。可是,UITextView就没那么幸运了,apple没有给UITextView提供一个类似于placeholder这样的属性来供开发者使用,但是需求中往往又需要用到UITextView这个控件且还需要占位符。所以,不多说,直接上代码:
unsigned int count = 0;
Ivar *ivars = class_copyIvarList([UITextView class], &count);
for (int i = 0; i < count; i++) {
Ivar ivar = ivars[i];
const char *name = ivar_getName(ivar);
NSString *objcName = [NSString stringWithUTF8String:name];
if ([objcName isEqualToString:@"_placeholderLabel"]) {
UILabel *placeHolderLabel = [[UILabel alloc] init];
placeHolderLabel.text = @"我是占位符";
placeHolderLabel.numberOfLines = 0;
placeHolderLabel.textColor = [UIColor lightGrayColor];
[placeHolderLabel sizeToFit];
[_surveyNoteTextView addSubview:placeHolderLabel];
placeHolderLabel.font = _surveyNoteTextView.font;
[_surveyNoteTextView setValue:placeHolderLabel forKey:@"_placeholderLabel"];
break;
}
}
free(ivars);
通过runtime,我发现,UITextView内部有一个名为“_placeHolderLabel”的私有成员变量。大家知道,Objective-C没有绝对的私有变量,因为我们可以通过KVC来访问私有变量。