为UITextView增加占位文字的封装

1.新建继承UITextView的类

定义可以对外访问用于修改的属性


/** 占位文字 */
@property (nonatomic, copy) NSString *placeholder;
/** 占位文字的颜色 */
@property (nonatomic, strong) UIColor *placeholderColor;

在.m文件定义一个label


/** 占位文字label */
@property (nonatomic, weak) UILabel *placeholderLabel;

懒加载把label添加到textView中

  • (UILabel *)placeholderLabel
    {
    if (!_placeholderLabel) {
    // 添加一个用来显示占位文字的label
    UILabel *placeholderLabel = [[UILabel alloc] init];
    placeholderLabel.numberOfLines = 0;
    placeholderLabel.x = 4;
    placeholderLabel.y = 7;
    [self addSubview:placeholderLabel];
    _placeholderLabel = placeholderLabel;
    }
    return _placeholderLabel;
    }
    参考文章:UIView扩展-直接用点语法改变UIView的尺寸http://www.jianshu.com/p/4e00189dea2b
初始化一些设置

  • (instancetype)initWithFrame:(CGRect)frame
    {
    if (self = [super initWithFrame:frame]) {
    // 垂直方向上永远有弹簧效果
    self.alwaysBounceVertical = YES;

      // 默认字体
      self.font = [UIFont systemFontOfSize:15];
      
      // 默认的占位文字颜色
      self.placeholderColor = [UIColor grayColor];
      
      // 监听文字改变
      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:nil];
    

    }
    return self;
    }

  • (void)textDidChange
    {
    // 只要有文字, 就隐藏占位文字label
    self.placeholderLabel.hidden = self.hasText;
    }

移除通知

  • (void)dealloc
    {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
更新占位文字的尺寸

  • (void)layoutSubviews
    {
    [super layoutSubviews];

    self.placeholderLabel.width = self.width - 2 * self.placeholderLabel.x;
    [self.placeholderLabel sizeToFit];
    }
    参考文章:UIView扩展-直接用点语法改变UIView的尺寸http://www.jianshu.com/p/4e00189dea2b

重写相关的setting方法

  • (void)setPlaceholderColor:(UIColor *)placeholderColor
    {
    _placeholderColor = placeholderColor;

    self.placeholderLabel.textColor = placeholderColor;
    }

  • (void)setPlaceholder:(NSString *)placeholder
    {
    _placeholder = [placeholder copy];

    self.placeholderLabel.text = placeholder;

    [self setNeedsLayout];
    }

  • (void)setFont:(UIFont *)font
    {
    [super setFont:font];

    self.placeholderLabel.font = font;

    [self setNeedsLayout];
    }

  • (void)setText:(NSString *)text
    {
    [super setText:text];

    [self textDidChange];
    }

  • (void)setAttributedText:(NSAttributedString*)attributedText
    {
    [super setAttributedText:attributedText];

    [self textDidChange];
    }

封装的类的下载地址https://git.oschina.net/qjz.com/TextView_placeholderLabel/tree/master

你可能感兴趣的:(为UITextView增加占位文字的封装)