標籤:
一看標題,就很屌絲!
的確,系統不給咱們,那咱們就自己弄!
具體步驟:
1,建立一個類,繼承UITextView.取名ZHHTextView;
2,在drawRect:中實現placeholder,其中用到通知來監聽text的change.
大概的步驟就著兩步,具體實現,看代碼.<一行代碼解千言>
現在將.m檔案代碼公布如下:
#import "ZHHTextView.h"
@implementation ZHHTextView
- (instancetype)initWithFrame:(CGRect)frame {
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 = 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);
NSString* placeholder = @"請輸入鴻歌的QQ...";
// 這個方法很經典
[placeholder drawInRect:placeholderRect withAttributes:attributes];
}
@end
OK了.
iOS&UITextView中的placeholder屬性