作為輸入框UITextField
和UITextView
各有優缺點,開發中經常需要使用到這兩個輸入框,UITextField
可以通過placeholder
這個屬性來加入占位文字,但不能換行;UITextView
雖然能自動換行,卻沒有placeholder這種方便的方式添加占位文字,雖然可以通過attributeString
來設置,但還是覺得不是特別方便。
最好的方法就是自定義一個UITextView
的子類PlaceholderView,那么這個類里面的任何內容都是你說了算,為UITextView
添加placeholder
功能只需要簡單的兩個步驟:一個通知和一個重寫drawRect
方法。
在初始化時添加通知
- (instancetype)initWithFrame:(CGRect)frame textContainer:(NSTextContainer *)textContainer {
self = [super initWithFrame:frame textContainer:textContainer];
if (self) {
[self registerNotification];
}
return self;
}
- (void)registerNotification {
[self unregisterNotification];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:nil];
}
通知方法里面告訴
UITextView
需要重繪
- (void)textDidChange {
[self setNeedsDisplay];
}
重繪視圖
- (void)drawRect:(CGRect)rect {
if ([self hasText]) {
return;
}
// 設置字體屬性
NSMutableDictionary *attrs = [NSMutableDictionary dictionaryWithCapacity:0];
attrs[NSFontAttributeName] = self.font;
attrs[NSForegroundColorAttributeName] = self.placeholderColor;
rect.origin.x = 5;
rect.origin.y = 7;
rect.size.width -= 2 * rect.origin.x;
rect.size.height -= 2 * rect.origin.y;
[self.placeholder drawInRect:rect withAttributes:attrs];
}