自定义带占位符placeholder的textView

自定义一个类,继承UITextView

.h文件

#import <UIKit/UIKit.h>

@interface WWMPlaceholderTextView : UITextView

/**
 占位文字
 */
@property (nonatomic, copy) NSString *placeholder;

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

@end

.m文件

#import "WWMPlaceholderTextView.h"

@implementation WWMPlaceholderTextView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
        //设置默认字体
        self.font = [UIFont systemFontOfSize:14];
        //设置默认颜色
        self.placeholderColor = [UIColor colorWithRed:191.0/255.0 green:191.0/255.0 blue:191.0/255.0 alpha:1.0];
        
        //使用通知监听文字改变
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:self];
    }
    return self;
}

//监听文字改变
- (void)textDidChange:(NSNotification *)notification{
    
    //重新调用drawRect:方法
    [self setNeedsDisplay];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/**
 调用drawRect

 @param rect 每次都会将以前的东西清除掉
 */
- (void)drawRect:(CGRect)rect{
    //如果有文字,直接返回,不需要占位文字
    if (self.hasText) {
        return;
    }
    
    //属性
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = self.font;
    attrs[NSForegroundColorAttributeName] = self.placeholderColor;
    
    //画文字
    rect.origin.x = 5;
    rect.origin.y = 8;
    rect.size.width -= 2*rect.origin.x;
    [self.placeholder drawInRect:rect withAttributes:attrs];
}

- (void)layoutSubviews{
    [super layoutSubviews];
    [self setNeedsDisplay];
}

#pragma mark -------setter
- (void)setPlaceholder:(NSString *)placeholder{
    _placeholder = placeholder;
    [self setNeedsDisplay];
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor{
    _placeholderColor = placeholderColor;
    [self setNeedsDisplay];
}
- (void)setFont:(UIFont *)font{
    [super setFont:font];
    [self setNeedsDisplay];
}
- (void)setText:(NSString *)text{
    [super setText:text];
    [self setNeedsDisplay];
}
- (void)setAttributedText:(NSAttributedString *)attributedText{
    [super setAttributedText:attributedText];
    [self setNeedsDisplay];
}

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

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,196评论 4 61
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,180评论 25 709
  • 墨客诗友酒大缸,和风入夜聚珠江 豪情再就抒怀志,直笔重回上膀杠 老树尖芽衍景象,吟哦妙律绕梁桩 岭南自古名流汇,一...
    螺河遊者阅读 1,482评论 0 0
  • via 盒子书生 眉目里似哭不似哭 还祈求什么说不出 陪着你轻呼着烟圈 到唇边 讲不出满足 你的温柔怎可以捕捉 越...
    盒子书生阅读 2,454评论 0 2
  • 念旧是一种什么样的情怀? 记住生命过往里出现的美好时刻和美好的人们。偶尔想起他们,脸上泛起真诚的微笑。 恋旧呢? ...
    真梨阅读 4,214评论 0 0