新浪微博客户端(36)-自定义带placeholder的TextView

本文介绍了一个自定义的iOS UITextView类,该类实现了显示占位符文本的功能。通过注册文本变化通知并重写绘制方法,实现在文本为空时显示灰色占位符。

iOS 上自带的UITextView竟然不能设置placeholder,但是UITextView却可以,我也真是醉了。没办法了,自己写一个

DJTextView.h

#import <UIKit/UIKit.h>

@interface DJTextView : UITextView


@property (nonatomic,copy) NSString *placeholder;
@property (nonatomic,strong) UIColor *placeholderColor;


@end

 

DJTextView.m

#import "DJTextView.h"

@implementation DJTextView


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // 在通知中心为TextView注册一个当文本改变的通知,当文本发生变化时,TextView会发一个通知
        // 类似于android里面的BroadcastReceiver
        // iOS 注册接收通知的方式为:addObserver name:
        // android 注册接收通知的方式为:intent.addAction();
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textHasChange) name:UITextViewTextDidChangeNotification object:self];
    }
    return self;
}



// 当文字改变时会调用此方法
- (void)textHasChange {

    // setNeedsDisplay 类似于android里面的postInvalidate()方法,都是向操作系统发出请求重绘的消息
    // 操作系统会在未来的时间内调用drawRect(iOS),onDraw(android);
    // 注意:系统不允许我们自己调用drawRect或onDraw方法
    [self setNeedsDisplay];

}



- (void)drawRect:(CGRect)rect {

    
    if ([self hasText]) return; // 如果检测到当前TextView中有文本,就不再绘制
    
    CGFloat placeholderRectX = 5;
    CGFloat placeholderRectY = 8;
    CGFloat placeholderRectW = rect.size.width - 2 * placeholderRectX;
    CGFloat placeholderRectH = rect.size.height - 2 * placeholderRectY;
    
    
    // 将文本绘制在一个指定的矩形框内
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = self.font;
     // 若用户没有设置placeholder的颜色,则给placeholder设置一个默认颜色
    attrs[NSForegroundColorAttributeName] = self.placeholderColor ? self.placeholderColor : [UIColor grayColor];
    [self.placeholder drawInRect:CGRectMake(placeholderRectX, placeholderRectY, placeholderRectW, placeholderRectH) withAttributes:attrs];
    

}



#pragma mark - 当用户手动更新当前字体属性时,就自动触发重绘
- (void)setText:(NSString *)text{

    [super setText:text];
    [self setNeedsDisplay];

}


- (void)setFont:(UIFont *)font {

    [super setFont:font];
    [self setNeedsDisplay];

}

- (void)setPlaceholder:(NSString *)placeholder {

    _placeholder = placeholder;
    [self setNeedsDisplay];

}


- (void)setPlaceholderColor:(UIColor *)placeholderColor {

    _placeholderColor = placeholderColor;
    [self setNeedsDisplay];

}



- (void)dealloc {

        // 类似于android,通知中心在使用完毕后需要销毁
        // iOS: [NSNotificationCenter defaultCenter] removeObserver:self]
        // android: unRegister(mBroadcastReceiver);
       [[NSNotificationCenter defaultCenter] removeObserver:self];

}



@end

最终效果:

 

转载于:https://www.cnblogs.com/yongdaimi/p/6099498.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值