您的位置:首页 > 产品设计 > UI/UE

iOS开发中利用runtime设置UITextView的默认文字

2017-07-17 18:17 288 查看
大家都知道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"];

如果对UITextView的默认文字要求不是很苛刻的话,这样就可以快速的设置UITextView的默认文字,可以提高我们的开发效率。
好了,本篇博客就到此结束了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐