起初,方法是在cell.contentView上加一个label,在UITextView开始编辑时在代理方法里隐藏label,结束编辑时如果UITextView没文字,再把label显示出来。相比如下方法显得麻烦。
下面是通过runtime打印发现的UITextView里有占位符私有变量,可通过KVC直接设置一个占位符,相对简单,而且是可以发布通过的。
// 通过运行时,发现UITextView有一个叫做“_placeHolderLabel”的私有变量
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];
NSLog(@"%d : %@",i,objcName);
}
static NSString *questionCellID = @"questionCellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:questionCellID];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:questionCellID];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UITextView *questionTV = [[UITextView alloc] initWithFrame:CGRectMake(15, 0, WID-30, 120)];
questionTV.font = [UIFont systemFontOfSize:12];
questionTV.textColor = [UIColor colorWithHexString:@"323232"];
questionTV.tag = 70;
[cell.contentView addSubview:questionTV];
// _placeholderLabel
UILabel *placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 12, CGRectGetWidth(questionTV.frame)-10, 14)];
placeHolderLabel.text = @"请描述您的病史、家族史及想要咨询的主题";
placeHolderLabel.numberOfLines = 0;
placeHolderLabel.textColor = [UIColor colorWithHexString:@"9a9a9a"];
placeHolderLabel.font = [UIFont systemFontOfSize:10];
placeHolderLabel.tag = 90;
[cell.contentView addSubview:placeHolderLabel];
}
UITextView *questionTV = (UITextView *)[cell.contentView viewWithTag:70];
questionTV.delegate = self;
questionTV.text = _question;
UILabel *placeHolderLabel = (UILabel *)[cell.contentView viewWithTag:90];
placeHolderLabel.hidden = (_question.length > 0 ? YES : NO);
return cell;
补充:经测试,上面的用KVC设置私有变量的方法,在iOS8上会崩掉,查看runtime打印的变量名没有_placeholderLabel,所以,还是老老实实往cell上加一个label吧。
设置textView的代理,然后加下面的代码
#pragma mark - UITextViewDelegate
-(void)textViewDidChange:(UITextView *)textView
{
_question = textView.text;
UITableViewCell *cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:4]];
UILabel *placeHolderLabel = (UILabel *)[cell.contentView viewWithTag:90];
if (textView.text.length == 0){
placeHolderLabel.hidden = NO;
}else{
placeHolderLabel.hidden = YES;
}
}