美文网首页
为UITextView增加占位文字的封装

为UITextView增加占位文字的封装

作者: 怪兽密保 | 来源:发表于2016-11-24 10:12 被阅读0次
1.新建继承UITextView的类

定义可以对外访问用于修改的属性
<pre>
/** 占位文字 */
@property (nonatomic, copy) NSString *placeholder;
/** 占位文字的颜色 */
@property (nonatomic, strong) UIColor *placeholderColor;
</pre>

在.m文件定义一个label

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

懒加载把label添加到textView中

<pre>

  • (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
    </pre>
初始化一些设置

<pre>

  • (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;
    }

</pre>

移除通知

<pre>

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

<pre>

  • (void)layoutSubviews
    {
    [super layoutSubviews];

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

重写相关的setting方法

<pre>

  • (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];
    }
    </pre>

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

相关文章

网友评论

      本文标题:为UITextView增加占位文字的封装

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