#import <UIKit/UIKit.h>
@interface PlaceholderTextView : UITextView
@property(nonatomic, strong)NSString *placeholder;
@property(nonatomic, strong)UIColor *placeholderColor;
@end
#import "PlaceholderTextView.h"
@interface PlaceholderTextView ()
@property(nonatomic, strong)UILabel *placeLable;
@end
@implementation PlaceholderTextView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
UILabel *placeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, 30)];
placeLabel.numberOfLines = 0;
placeLabel.backgroundColor = [UIColor clearColor];
[self addSubview:placeLabel];
self.placeLable = placeLabel;
self.font = [UIFont systemFontOfSize:16.0];
self.placeholderColor = [UIColor grayColor];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged) name:UITextViewTextDidChangeNotification object:self];
}
return self;
}
-(void)setPlaceholder:(NSString *)placeholder{
_placeholder = [placeholder copy];
self.placeLable.text = _placeholder;
[self setNeedsLayout];
}
-(void)setPlaceholderColor:(UIColor *)placeholderColor{
_placeholderColor = placeholderColor;
self.placeLable.textColor = _placeholderColor;
}
-(void)layoutSubviews{
[super layoutSubviews];
CGRect temp = _placeLable.frame;
temp.origin.y = 8.0f;
temp.origin.x = 5.0f;
temp.size.width = self.frame.size.width - 2*temp.origin.x;
CGSize size = [self.placeLable sizeThatFits:CGSizeMake(temp.size.width, MAXFLOAT)];
self.placeLable.frame = CGRectMake(5, 8, temp.size.width,size.height);
}
-(void)setFont:(UIFont *)font{
[super setFont:font];
self.placeLable.font = font;
[self setNeedsLayout];
}
-(void)setText:(NSString *)text{
[super setText:text];
[self textChanged];
}
-(void)textChanged{
if (self.text.length == 0) {
self.placeLable.hidden = NO;
}else{
self.placeLable.hidden = YES;
}
}
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
有placeholder的UITextView
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 在开发的时候我们经常会使用到UITextField和UITextView,这两者很像,但是UITextView没有...
- 开发中系统自带的UITextView没有placeHolder属性,于是万能的开发者们想出了很多办法,看到简书上V...