有的时候在使用textView的时候需要设置一些placeholder, 但是发现textView并没有类似textField的placeholder属性,那么要想实现类似textField的placeholder效果需要自己自定义一个textView,
代码如下
定义一个全局的placeholderLabel,用来显示placeholder
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if(self) {
self.backgroundColor= [UIColor clearColor];
UILabel *placeholderLabel = [[UILabel alloc]init];//添加一个占位label
placeholderLabel.backgroundColor= [UIColor clearColor];
placeholderLabel.numberOfLines=0; //设置可以输入多行文字时可以自动换行
[self addSubview:placeholderLabel];
self.placeholderLabel= placeholderLabel; //赋值保存
self.placeholderColor= [UIColor lightGrayColor]; //设置占位文字默认颜色
self.placeholderLabel.font= [UIFont systemFontOfSize:15]; //设置默认的字体
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self]; //通知:监听文字的改变
}
return self;
}
- (void)textDidChange
{
//hasText 输入文字就是yes
self.placeholderLabel.hidden = self.hasText;
}
- (void)layoutSubviews
{
[super layoutSubviews];
self.placeholderLabel.y = 8;
self.placeholderLabel.x=5;//设置 UILabel 的 x 值
self.placeholderLabel.width=self.width-self.placeholderLabel.x*2.0; //设置 UILabel 的 x
//根据文字计算高度
CGSize maxSize =CGSizeMake(self.placeholderLabel.width,MAXFLOAT);
self.placeholderLabel.height= [self.placeholder boundingRectWithSize:maxSize options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : self.placeholderLabel.font} context:nil].size.height;
}
- (void)setPlaceholder:(NSString *)placeholder
{
_placeholder = [placeholder copy];
self.placeholderLabel.text = placeholder;
//重新计算子控件frame
[self setNeedsLayout];
}
- (void)setPlaceholderFont:(UIFont *)placeholderFont
{
_placeholderFont = placeholderFont;
self.placeholderLabel.font = _placeholderFont;
}
- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
_placeholderColor = placeholderColor;
//设置颜色
self.placeholderLabel.textColor= placeholderColor;
}
//重写这个set方法保持font一致
- (void)setFont:(UIFont*)font {
[super setFont:font];
self.placeholderLabel.font= font;
//重新计算子控件frame
[self setNeedsLayout];
}
- (void)setText:(NSString*)text{
[super setText:text];
[self textDidChange]; //这里调用的就是 UITextViewTextDidChangeNotification 通知的回调
}
- (void)setAttributedText:(NSAttributedString*)attributedText {
[super setAttributedText:attributedText];
[self textDidChange]; //这里调用的就是UITextViewTextDidChangeNotification 通知的回调
}
- (void)dealloc{
[[NSNotificationCenter defaultCenter]removeObserver:UITextViewTextDidChangeNotification];
}
demo下载地址:http://download.csdn.net/detail/qq_31927183/9553359
github:https://github.com/lwy121810/WYPlaceholderTextView