.h
文件
#import <UIKit/UIKit.h>
@interface XMGPlaceholderTextView : UITextView
/** 占位文字 */
@property (nonatomic, copy) NSString *placeholder;
/** 占位文字的顏色 */
@property (nonatomic, strong) UIColor *placeholderColor;
@end
.m
文件
#import "XMGPlaceholderTextView.h"
@interface XMGPlaceholderTextView()
/** 占位文字label */
@property (nonatomic, weak) UILabel *placeholderLabel;
@end
@implementation XMGPlaceholderTextView
- (UILabel *)placeholderLabel
{
if (!_placeholderLabel) {
// 添加一個用來顯示占位文字的label
UILabel *placeholderLabel = [[UILabel alloc] init];
placeholderLabel.numberOfLines = 0;
CGRect rect = placeholderLabel.frame;
rect.origin.x = 4;
rect.origin.y = 7;
placeholderLabel.frame = rect;
[self addSubview:placeholderLabel];
_placeholderLabel = placeholderLabel;
}
return _placeholderLabel;
}
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
// 垂直方向上永遠有彈簧效果
self.alwaysBounceVertical = YES;
// 默認字體
self.font = [UIFont systemFontOfSize:15];
// 默認的占位文字顏色
self.placeholderColor = [UIColor grayColor];
// 監聽文字改變
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:nil];
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
/**
* 監聽文字改變
*/
- (void)textDidChange
{
// 只要有文字, 就隱藏占位文字label
self.placeholderLabel.hidden = self.hasText;
}
/**
* 更新占位文字的尺寸
*/
- (void)layoutSubviews
{
[super layoutSubviews];
CGRect rect = self.placeholderLabel.frame;
rect.size.width = self.frame.size.width - 2 * self.placeholderLabel.frame.origin.x;
self.placeholderLabel.frame = rect;
[self.placeholderLabel sizeToFit];
}
#pragma mark - 重寫setter
- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
_placeholderColor = placeholderColor;
self.placeholderLabel.textColor = placeholderColor;
}
- (void)setPlaceholder:(NSString *)placeholder
{
_placeholder = [placeholder copy];
self.placeholderLabel.text = placeholder;
[self setNeedsLayout];
}
- (void)setFont:(UIFont *)font
{
[super setFont:font];
self.placeholderLabel.font = font;
[self setNeedsLayout];
}
- (void)setText:(NSString *)text
{
[super setText:text];
[self textDidChange];
}
- (void)setAttributedText:(NSAttributedString *)attributedText
{
[super setAttributedText:attributedText];
[self textDidChange];
}
/**
* setNeedsDisplay方法 : 會在恰當的時刻自動調用drawRect:方法
* setNeedsLayout方法 : 會在恰當的時刻調用layoutSubviews方法
*/
@end
說明:出自MJ