UITextView添加占位文字和占位文字顏色
具體實現(xiàn)
.h文件
#import <UIKit/UIKit.h>
@interface FMTextViewPlaceholder : UITextView
/** 占位文字 */
@property (nonatomic, strong) NSString *placeholderWord;
/** 占位文字顏色 */
@property (nonatomic, weak) UIColor *placeholderColor;
@end
.m文件
#import "FMTextViewPlaceholder.h"
@implementation FMTextViewPlaceholder
- (void)awakeFromNib {
[super awakeFromNib];
self.font = [UIFont systemFontOfSize:15];
// 監(jiān)聽文字的改變
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:self];
}
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.font = [UIFont systemFontOfSize:15];
// 監(jiān)聽文字的改變
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextViewTextDidChangeNotification object:self];
}
return self;
}
- (void)textDidChange:(NSNotification *)note {
// 會重新調(diào)用drawRect:方法
[self setNeedsDisplay];
}
#pragma mark - setter方法
- (void)setPlaceholderWord:(NSString *)placeholderWord {
_placeholderWord = placeholderWord;
// 重繪
[self setNeedsDisplay];
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor {
_placeholderColor = placeholderColor;
[self setNeedsDisplay];
}
- (void)setText:(NSString *)text {
[super setText:text];
[self setNeedsDisplay];
}
- (void)setFont:(UIFont *)font {
[super setFont:font];
[self setNeedsDisplay];
}
- (void)setAttributedText:(NSAttributedString *)attributedText {
[super setAttributedText:attributedText];
[self setNeedsDisplay];
}
#pragma mark - 系統(tǒng)方法
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)layoutSubviews {
[super layoutSubviews];
[self setNeedsDisplay];
}
/**
* 每次調(diào)用這個方法就會把上一次繪制清空
*
*/
- (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 -= rect.origin.x * 2;
[self.placeholderWord drawInRect:rect withAttributes:attrs];
}
@end