带占位文字的TextView

作为输入框UITextFieldUITextView各有优缺点,开发中经常需要使用到这两个输入框,UITextField可以通过placeholder这个属性来加入占位文字,但不能换行;UITextView虽然能自动换行,却没有placeholder这种方便的方式添加占位文字,虽然可以通过attributeString来设置,但还是觉得不是特别方便。
最好的方法就是自定义一个UITextView的子类PlaceholderView,那么这个类里面的任何内容都是你说了算,为UITextView添加placeholder功能只需要简单的两个步骤:一个通知和一个重写drawRect方法。

在初始化时添加通知

- (instancetype)initWithFrame:(CGRect)frame textContainer:(NSTextContainer *)textContainer {

    self = [super initWithFrame:frame textContainer:textContainer];
    if (self) {
        [self registerNotification];
    }
    return self;
}

- (void)registerNotification {
    [self unregisterNotification];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:nil];

}

通知方法里面告诉UITextView需要重绘

- (void)textDidChange {
    [self setNeedsDisplay];
}

重绘视图

- (void)drawRect:(CGRect)rect {
    if ([self hasText]) {
        return;
    }

    // 设置字体属性

    NSMutableDictionary *attrs = [NSMutableDictionary dictionaryWithCapacity:0];

    attrs[NSFontAttributeName] = self.font;

    attrs[NSForegroundColorAttributeName] = self.placeholderColor;

    rect.origin.x = 5;
    rect.origin.y = 7;
    rect.size.width -= 2 * rect.origin.x;
    rect.size.height -= 2 * rect.origin.y;
    [self.placeholder drawInRect:rect withAttributes:attrs];
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容