注冊UITextViewTextDidChangeNotification 通知,每次文字改變的時候會重新調用drawRect方法席舍,重新繪制placeholder。
@interface MyTextView : UITextView
/** 占位文字 */
@property (nonatomic, copy) NSString *placeholder;
/** 占位文字的顏色 */
@property (nonatomic, strong) UIColor *placeholderColor;
@end
@implementation MyTextView
-(instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
// 當UITextView的文字發(fā)生改變時咽笼,UITextView自己會發(fā)出一個UITextViewTextDidChangeNotification通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
/**
* 監(jiān)聽文字改變
*/
- (void)textDidChange
{
// 重繪(重新調用)
[self setNeedsDisplay];
}
- (void)setPlaceholder:(NSString *)placeholder
{
_placeholder = [placeholder copy];
[self setNeedsDisplay];
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
_placeholderColor = placeholderColor;
[self setNeedsDisplay];
}
- (void)setText:(NSString *)text
{
[super setText:text];
// setNeedsDisplay會在下一個消息循環(huán)時刻招刨,調用drawRect:
[self setNeedsDisplay];
}
- (void)setFont:(UIFont *)font
{
[super setFont:font];
[self 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];
}