相信小伙伴们,都在对于 UITextView 没有placeholder属性而感到苦恼吧。
当我在使用 runtime 遍历 UITextView的所有属性时, 发现了有一个叫做 _placeholderLabel的家伙。
好吧,没有绝对的私有属性的情况下,我们可以使用kvc 来修改 私有属性。
下面就上代码了。
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 100, [UIScreenmainScreen].bounds.size.width - 100, 100)];
[textView setBackgroundColor:[UIColor greenColor]];
textView.font = [UIFont systemFontOfSize:15];
[self.view addSubview:textView];
// _placeholderLabel
UILabel *placeholderLabel = [[UILabel alloc] init];
placeholderLabel.text = @"请输入文本内容";
placeholderLabel.numberOfLines = 1;
placeholderLabel.textColor = [UIColor lightGrayColor];
[placeholderLabel sizeToFit];
placeholderLabel.font = textView.font; //如果不设置font 为textView的font大小,第一次 placeholderLabel要偏移哦
[textView addSubview:placeholderLabel];
[textView setValue:placeholderLabel forKey:@"_placeholderLabel"];
赶紧尝试尝试吧!!