发微博文本框-文字变化实现

当有文字输入时,UITextView上的默认文字消失,没有任何输入时,显示默认文字。

做法:

1. 在自定义UITextView的初始化方法- (id)initWithFrame:(CGRect)frame里面注册通知,监听文本变化:

// 当UITextView的文字发生改变时,UITextView自己会发出一个UITextViewTextDidChangeNotification通知,执行textDidChange方法
        [HWNotificationCenter addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];

2. 调setNeedsDisplay 触发drawRect 方法

/**
 * 监听文字改变
 */
- (void)textDidChange
{
    // 重绘(重新调用)
    [self setNeedsDisplay];
}

// 重绘方法由setNeedsDisplay来触发
- (void)drawRect:(CGRect)rect
{
    // 如果有输入文字,就直接返回,不画占位文字
    if (self.hasText) return;
    
    // 文字属性
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = self.font;
    attrs[NSForegroundColorAttributeName] = self.placeholderColor?self.placeholderColor:[UIColor grayColor];
    // 画文字
    CGFloat x = 5;
    CGFloat w = rect.size.width - 2 * x;
    CGFloat y = 8;
    CGFloat h = rect.size.height - 2 * y;
    CGRect placeholderRect = CGRectMake(x, y, w, h);
    [self.placeholder drawInRect:placeholderRect withAttributes:attrs];//这个方法能保证默认文字多行时,隐藏默认文字
}
此文仅为鄙人学习笔记之用,朋友你来了,如有不明白或者建议又或者想给我指点一二,请私信我。liuw_flexi@163.com/QQ群:582039935. 我的gitHub: (学习代码都在gitHub) https://github.com/nwgdegitHub/
原文地址:https://www.cnblogs.com/liuw-flexi/p/7535657.html