其實(shí)需求很簡單,想必你也會(huì)攒钳!但是萬一有需要的同學(xué)呢帮孔!廢話少說,看需求效果圖:
textView正常情況下是沒有占位符的,但是我們可以通過繼承與textview 用他的drawRect方法繪制文兢,代碼如下:
.h文件中添加屬性
@interface DXFeedBackTextView : UITextView
/** 占位文字 /
@property(nonatomic, copy) NSString placeholder;
/ 占位文字顏色 */
@property(nonatomic, strong) UIColor *placeholderColor;
@end
.m文件中實(shí)現(xiàn)代碼如:
@implementation DXFeedBackTextView
- (instancetype)init{
if (self = [super init]) {
// 設(shè)置默認(rèn)字
self.font = [UIFont systemFontOfSize:17];
// 設(shè)置默認(rèn)顏色
self.placeholderColor = [UIColor grayColor];
// 使用通知監(jiān)聽文字改變
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:self];
}
return self;
}
- (void)textDidChange:(NSNotification *)note{
// 會(huì)重新調(diào)用drawRect:方法
[self setNeedsDisplay];
}
- (void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
/**
* 每次調(diào)用drawRect:方法晤斩,都會(huì)將以前畫的東西清除掉
*/
- (void)drawRect:(CGRect)rect{
// 如果有文字,就直接返回姆坚,不需要畫占位文字
if (self.hasText) return;
// 屬性
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSFontAttributeName] = self.font;
attrs[NSForegroundColorAttributeName] = self.placeholderColor;
// 畫文字
rect.origin.x = 5;
rect.origin.y = 8;
rect.size.width -= 2 * rect.origin.x;
[self.placeholder drawInRect:rect withAttributes:attrs];
}
- (void)layoutSubviews{
[super layoutSubviews];
[self setNeedsDisplay];
}
#pragma mark - setter
//重寫setter方法調(diào)用setNeedsDisplay方法刷新
- (void)setPlaceholder:(NSString *)placeholder{
_placeholder = [placeholder copy];
[self setNeedsDisplay];
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor{
_placeholderColor = placeholderColor;
[self setNeedsDisplay];
}
- (void)setFont:(UIFont *)font{
[super setFont:font];
[self setNeedsDisplay];
}
- (void)setText:(NSString *)text{
[super setText:text];
[self setNeedsDisplay];
}
- (void)setAttributedText:(NSAttributedString *)attributedText{
[super setAttributedText:attributedText];
[self setNeedsDisplay];
}
@end
打完收工澳泵!