標籤:string blog ios publish name 自動 bsp rect return
@interface BSPublishTextView : UITextView
/** 對外屬性佔位字元 placeholder */
@property (nonatomic, copy) NSString *placeholder;
/** 對外屬性預留位置顏色 */
@property (nonatomic, strong) UIColor *placeholderColor;
@end
@interface BSPublishTextView ()
/** 佔位字元 label */
@property (nonatomic, weak) UILabel *placeholderLabel;
@end
@implementation BSPublishTextView
- (UILabel *)placeholderLabel{
if (!_placeholderLabel) {
UILabel *placeholderLabel = [[UILabel alloc]init];
placeholderLabel.backgroundColor = [UIColor greenColor];
placeholderLabel.numberOfLines = 0;
placeholderLabel.x = 4;
placeholderLabel.y = 7;
[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];
// 註冊通知 當收到 UITextViewTextDidChangeNotification textView文字改變時
[[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佔位字元的寬度
self.placeholderLabel.width = self.width - 2 * self.placeholderLabel.x;
// 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
iOS中用UILabel實現UITextView的佔位文字