自定義UITextView豪诲,在.h中
@interface JJPlaceHTextView : UITextView
/** 占位文字 */
@property (nonatomic, copy) NSString *placeholder;
/** 占位文字顏色 */
@property (nonatomic, strong) UIColor *placeholderColor;
@end
在.m中
- (instancetype)init
{
if (self = [super init]) {
// 設置默認字體
self.font = [UIFont systemFontOfSize:15];
// 設置默認顏色
self.placeholderColor = ColorA9;
// 使用通知監(jiān)聽文字改變
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:self];
}
return self;
}
- (void)textDidChange:(NSNotification *)note
{
// 會重新調用drawRect:方法
[self setNeedsDisplay];
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
/**
* 每次調用drawRect:方法劳翰,都會將以前畫的東西清除掉
*/
- (void)drawRect:(CGRect)rect
{
// 如果有文字绘闷,就直接返回巢价,不需要畫占位文字
if (self.hasText) return;
// 屬性
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSFontAttributeName] = self.font;
attrs[NSForegroundColorAttributeName] = self.placeholderColor;
// 畫文字
rect.origin.x = 0;
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
- (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];
}