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

当有文字输入时,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];//这个方法能保证默认文字多行时,隐藏默认文字
}

 

posted @ 2017-09-17 15:03  liuw_flexi  阅读(301)  评论(0编辑  收藏  举报