美文网首页
iOS之给TextView增加placeholder

iOS之给TextView增加placeholder

作者: 张大普奔 | 来源:发表于2017-06-28 19:00 被阅读33次

    利用两个UITextView非常简单的实现给TextView增加placeholder的功能

    .h

    #import <UIKit/UIKit.h>
    
    @interface ZCTextView : UIView
    
    @property (nonatomic, strong) UITextView *placeholderTextView;
    @property (nonatomic, strong) UITextView *textView;
    
    @end
    

    .m

    #import "ZCTextView.h"
    
    @interface ZCTextView()<UITextViewDelegate>
    
    @end
    
    @implementation ZCTextView
    
    - (instancetype)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
        if (self) {
            [self addSubview:self.placeholderTextView];
            [self addSubview:self.textView];
        }
        return self;
    }
    
    - (UITextView *)placeholderTextView
    {
        if (!_placeholderTextView) {
            _placeholderTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, 0, self.width-20, self.height)];
            _placeholderTextView.font = [UIFont systemFontOfSize:15];
            _placeholderTextView.textColor = UIColorFromRGB(0xcdcdcd);
            _placeholderTextView.backgroundColor = [UIColor clearColor];
        }
        return _placeholderTextView;
    }
    
    - (UITextView *)textView
    {
        if (!_textView) {
            _textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 0, self.width-20, self.height)];
            _textView.font = [UIFont systemFontOfSize:15];
            _textView.textColor = UIColorFromRGB(0x595959);
            _textView.backgroundColor = [UIColor clearColor];
            _textView.delegate = self;
        }
        return _textView;
    }
    
    - (void)textViewDidBeginEditing:(UITextView *)textView
    {
        _placeholderTextView.hidden = YES;
    }
    
    - (void)textViewDidChangeSelection:(UITextView *)textView
    {
        if (STR_IS_NOT_EMPTY(self.textView.text)) {
            _placeholderTextView.hidden = YES;
        }else{
            _placeholderTextView.hidden = NO;
        }
    }
    
    - (void)textViewDidEndEditing:(UITextView *)textView
    {
        if (STR_IS_NOT_EMPTY(self.textView.text)) {
            _placeholderTextView.hidden = YES;
        }else{
            _placeholderTextView.hidden = NO;
        }
    }
    
    @end
    

    举例

    @property (nonatomic, strong) ZCTextView *ContentTextView;
    
    - (ZCTextView *)ContentTextView
    {
        if (!_ContentTextView) {
            _ContentTextView = [[ZCTextView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 150)];
            _ContentTextView.placeholderTextView.text = @"这是默认提示文字";
            _ContentTextView.backgroundColor = [UIColor whiteColor];
        }
        return _ContentTextView;
    }
    

    相关文章

      网友评论

          本文标题:iOS之给TextView增加placeholder

          本文链接:https://www.haomeiwen.com/subject/zqxpcxtx.html