一看標題,就很屌絲!ide
的確,系統不給我們,那我們就本身弄!spa
具體步驟:code
1,建立一個類,繼承UITextView.取名ZHHTextView;orm
2,在drawRect:中實現placeholder,其中用到通知來監聽text的change.server
大概的步驟就着兩步,具體實現,看代碼.<一行代碼解千言>繼承
如今將.m文件代碼公佈以下:rem
#import "ZHHTextView.h"animation
@implementation ZHHTextView同步
- (instancetype)initWithFrame:(CGRect)frame {it
if (self = [super initWithFrame:frame]) {
NSLog(@"%s",__func__);
//註冊通知.要用到通知的用意:監聽內容的變化
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewTextChange) name:UITextViewTextDidChangeNotification object:nil];
}
return self;
}
- (void)viewTextChange {
// 執行此方法,系統自動調用drawRect:方法
[self setNeedsDisplay];
NSLog(@"%s",__func__);
}
- (void)dealloc {
//取消通知,你不取消試試,看你的項目會不會崩
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
// 若是有內容,則返回
if (self.hasText)return;
// 給placeholder添加屬性
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
//這裏最好仍是要與self.font同步
attributes[NSFontAttributeName] = [UIFont systemFontOfSize:15.0];
attributes[NSForegroundColorAttributeName] = [UIColor grayColor];
// 其實placeholder是畫上去的,既然是畫上去的,必須給定具體的位置與尺寸
CGFloat x = 15;
CGFloat w = rect.size.width - 2 * x;
CGFloat y = 12;
CGFloat h = rect.size.height - 2 * y;
CGRect placeholderRect = CGRectMake(x, y, w, h);
NSString* placeholder = @"請輸入鴻歌的QQ...";
// 這個方法很經典
[placeholder drawInRect:placeholderRect withAttributes:attributes];
}
@end
OK了.