UITextView自己沒有默認的占位符,如果有需求我們一般都會自己加一個拍霜,方法有很多,比如說自己建一個Label祠饺,監(jiān)聽UITextView的文字變化來修改Label的狀態(tài)等等。
這里我們用到一個UITextView私有屬性_placeholderLabel汁政,這個屬性貌似是需要ios8.3之后的版本才能使用,而且以后會不會有也不知道烂完。因為用到了系統(tǒng)私有變量,怕上架被拒抠蚣。所以慎用。
先在UITextView的分類里加個屬性
@property (nonatomic, strong ,readonly) UILabel *placeholderLabel;
然后補上它的get和set方法嘶窄。
- (UILabel *)placeholderLabel {
UILabel *placeholderLabel = objc_getAssociatedObject(self, _cmd);
if (!placeholderLabel) {
placeholderLabel = [[UILabel alloc] init];
placeholderLabel.numberOfLines = 0;
placeholderLabel.textColor = [UIColor lightGrayColor];
placeholderLabel.font = self.font ? self.font : [UIFont systemFontOfSize:17];
[placeholderLabel sizeToFit];
[self addSubview:placeholderLabel];
@try { [self setValue:placeholderLabel forKey:@"_placeholderLabel"]; } @catch (NSException *exception) {} @finally {}
[self addObserver:self forKeyPath:@"font" options:NSKeyValueObservingOptionNew context:nil];
self.placeholderLabel = placeholderLabel;
}
return placeholderLabel;
}
- (void)setPlaceholderLabel:(UILabel *)placeholderLabel {
objc_setAssociatedObject(self, @selector(placeholderLabel), placeholderLabel, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
這里 placeholderLabel.font = self.font ? self.font : [UIFont systemFontOfSize:17];
這句話一定要有,否則有可能會移位柄冲,原因是這時的UITextView的font可能為nil。
這里 @try { [self setValue:placeholderLabel forKey:@"_placeholderLabel"]; } @catch (NSException *exception) {} @finally {} 防止老版本沒有這個屬性现横。
再把監(jiān)聽font屬性加上
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"font"]) self.placeholderLabel.font = [change objectForKey:@"new"];
}
最后別忘了釋放監(jiān)聽
- (void)dealloc {
if (objc_getAssociatedObject(self, @selector(placeholderLabel))) [self removeObserver:self forKeyPath:@"font"];
}
這樣基本上就可以使用了阁最。
調(diào)用直接設置placeholderLabel的text
UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
[self.view addSubview:textView];
textView.placeholderLabel.text = @"占位符測試";
textView.font = [UIFont systemFontOfSize:26];