UITextView实现占位文字

实现输入框多行占位文字的方案有两种

  • UITextView实现
  • UILabel实现

自定义UITextView,作如下封装

  • 提供给外界设置占位文字和文字颜色的接口
/**占位文字 */
@property (nonatomic, copy) NSString *placeholder;
/**占位文字颜色 */
@property (nonatomic, strong) UIColor *placeholderColor;
  • 初始化方法中(提供默认字体和颜色是为了如果别人不进行特殊设置,采用默认设置)
-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        //监听
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(xmg_textViewDidChange) name:UITextViewTextDidChangeNotification object:nil];
        //默认灰色
        self.placeholderColor = [UIColor lightGrayColor];
        //默认字体
        self.font = [UIFont systemFontOfSize:14];
    }
    return self;
}
  • 监听文字改变实时重绘
//每次重绘之前都会清空上一次
-(void)drawRect:(CGRect)rect
{
    if ([self hasText]) return;
    rect.origin.x = 3;
    rect.origin.y = 7;
    rect.size.width -= 2 * rect.origin.x;
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = self.placeholderColor;
    attrs[NSFontAttributeName] = self.font;
    [_placeholder drawInRect:rect withAttributes:attrs];
}
  • 实现以下方法(修改文字,样式实时重绘)
-(void)xmg_textViewDidChange
{
    [self setNeedsDisplay];
}
-(void)setPlaceholder:(NSString *)placeholder
{
    _placeholder = [placeholder copy];
    [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];
}
-(void)setTextColor:(UIColor *)textColor
{
    [super setTextColor:textColor];
    [self setNeedsDisplay];
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

你可能感兴趣的:(UITextView实现占位文字)