@interface BSPublishTextView ()io
/** 佔位字符 label */class
@property (nonatomic, weak) UILabel *placeholderLabel;object
@endselect
@implementation BSPublishTextView
- (UILabel *)placeholderLabel{
if (!_placeholderLabel) {
UILabel *placeholderLabel = [[UILabel alloc]init];
placeholderLabel.numberOfLines = 0;
CGRect frame = placeholderLabel.frame;
frame.origin.x = 4;
frame.origin.y = 7;
placeholderLabel.frame = frame;
[self addSubview:placeholderLabel];
_placeholderLabel = placeholderLabel;
}
return _placeholderLabel;
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// 永久垂直彈簧效果
self.alwaysBounceVertical = YES;
self.font = [UIFont systemFontOfSize:15];
self.placeholderColor = [UIColor grayColor];
// 註冊textView文字發生改變通知 UITextViewTextDidChangeNotification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextViewTextDidChangeNotification object:nil];
}
return self;
}
//通知調用方法
- (void)textChange{
self.placeholderLabel.hidden = self.hasText;
}
- (void)dealloc{
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)layoutSubviews{
[super layoutSubviews];
//在 layoutSubviews 拿到 UITextView的寬度必定是正確的 ,這裏若是外界即便更改了UITextView的寬度這裏也是能算正確的
//先設置placeholderLabel佔位字符的寬度
CGRect frame = self.placeholderLabel.frame;
frame.size.width = self.frame.size.width - 2 * self.placeholderLabel.frame.origin.x;
self.placeholderLabel.frame = frame;
// placeholderLabel佔位字符的大小size隨裏面的內容大小而變化
[self.placeholderLabel sizeToFit];
}
// setNeedsDisplay方法 : 會在恰當的時刻自動調用drawRect:方法
// setNeedsLayout方法 : 會在恰當的時刻調用layoutSubviews方法
- (void)setPlaceholderColor:(UIColor *)placeholderColor{
_placeholderColor = placeholderColor;
self.placeholderLabel.textColor = placeholderColor;
}
- (void)setPlaceholder:(NSString *)placeholder{
_placeholder = [placeholder copy];
self.placeholderLabel.text = placeholder;
[self setNeedsLayout]; //會在恰當的時刻調用layoutSubviews方法 這句代碼可不寫
}
- (void)setFont:(UIFont *)font{
[super setFont:font];
self.placeholderLabel.font = font;
[self setNeedsLayout]; //會在恰當的時刻調用layoutSubviews方法 這句代碼可不寫
}
- (void)setText:(NSString *)text{
[super setText:text];
[self textChange];
}
- (void)setAttributedText:(NSAttributedString *)attributedText{
[super setAttributedText:attributedText];
[self textChange];
}
@end