iOS adds placeholder to UITextView

    In iOS development, we often use UITextField and UITextView. When using UITextField, the system will provide its own placeholder attribute, but not in UITextView. So how to set the placeholder in UITextView, as shown below:

method one:

#pragma mark - 懒加载
- (UITextView *)textView {
    if (!_textView) {
        _textView = [UITextView new];
        _textView.backgroundColor = [UIColor lightGrayColor];
        _textView.layer.cornerRadius = 5;
        _textView.font = [UIFont systemFontOfSize:12]; //注意必须设置字体大小,不然在UI显示时会出现placeholder字体上移的情况
        
        UILabel *placeHolderLabel = [[UILabel alloc] init];
        placeHolderLabel.text = @"请输入内容";
        placeHolderLabel.numberOfLines = 0;
        placeHolderLabel.textColor = [UIColor lightGrayColor];
        [placeHolderLabel sizeToFit];
        placeHolderLabel.font = [UIFont systemFontOfSize:12];
        [_textView addSubview:placeHolderLabel];
        [_textView setValue:placeHolderLabel forKey:@"_placeholderLabel"];
    }
    return _textView;
}

Method 2: Use the third-party library UITextView+Placeholder

Direct pod 'UITextView+Placeholder'

Then #import "UITextView+Placeholder.h" on the page you need to use

When used as follows:

textView.placeholder = @"请输入内容";

 

Guess you like

Origin blog.csdn.net/qq_37269542/article/details/107457893