大家都知道UITextField有一个属性placeholder是用来设置默认文字的,但不知道大家知不知道UITextView也有一个类似的属性是可以用来设置默认文字的(反正在今天之前我是不知道的)。之前在项目中也遇到过设置UITextView的默认文字的功能,当初的做法是在UITextView上添加一个UILabel,让UILabel来显示UITextView的默认文字。今天在看别人的博客的时候发现了UITextField有一个placeholderLabel的属性,这个属性是UITextView的私有属性,我们可以通过runtime访问该属性。我们可以通过创建一个UILabel,然后利用KVC将UITextView的placeholderLabel替换成我们自己创建的UILabel来达到设置UITextView默认文字的功能。代码:
_textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 50, [UIScreen mainScreen].bounds.size.width, 200)];
_textView.delegate = self;
_textView.tintColor = [UIColor blueColor];
_textView.font = [UIFont systemFontOfSize:15.f];
_textView.backgroundColor =[UIColor grayColor];
[self.view addSubview:_textView];
UILabel *placeholderLabel = [[UILabel alloc] init];
placeholderLabel.text = @"这是默认文字。。。";
placeholderLabel.font = [UIFont systemFontOfSize:15.f];
placeholderLabel.textColor = [UIColor whiteColor];
placeholderLabel.numberOfLines = 0;
[placeholderLabel sizeToFit];
[_textView addSubview:placeholderLabel];
[_textView setValue:placeholderLabel forKey:@"_placeholderLabel"];
好了,本篇博客就到此结束了。