代码待封装的textview
Posted chims-liu-touch
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了代码待封装的textview相关的知识,希望对你有一定的参考价值。
@interface HATextView : UITextView
@property(nonatomic,copy) NSString *myPlaceholder; //文字
@property(nonatomic,strong) UIColor *myPlaceholderColor;
@end
@interface HATextView()
@property (nonatomic,weak) UILabel *placeholderLabel;
@end
@implementation HATextView
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if(self) {
self.backgroundColor= [UIColor clearColor];
UILabel *placeholderLabel = [[UILabel alloc]init];//添加一个占位label
placeholderLabel.font = [UIFont systemFontOfSize:14];
placeholderLabel.backgroundColor = [UIColor clearColor];
placeholderLabel.numberOfLines = 0; //设置可以输入多行文字时可以自动换行
[self addSubview:placeholderLabel];
self.placeholderLabel= placeholderLabel; //赋值保存
self.myPlaceholderColor= [UIColor lightGrayColor]; //设置占位文字默认颜色
self.font= [UIFont systemFontOfSize:14]; //设置默认的字体
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self]; //通知:监听文字的改变
}
return self;
}
- (void)textDidChange {
self.placeholderLabel.hidden = self.hasText;
}
- (void)layoutSubviews{
[super layoutSubviews];
self.placeholderLabel.frame = CGRectMake(8, 6, 200, 16);
}
- (void)setMyPlaceholder:(NSString*)myPlaceholder{
_myPlaceholder= [myPlaceholder copy];
//设置文字
self.placeholderLabel.text = myPlaceholder;
//重新计算子控件frame
[self setNeedsLayout];
}
- (void)setMyPlaceholderColor:(UIColor*)myPlaceholderColor{
_myPlaceholderColor= myPlaceholderColor;
self.placeholderLabel.textColor= myPlaceholderColor;
}
- (void)setFont:(UIFont*)font{
[super setFont:font];
self.placeholderLabel.font= font;
//重新计算子控件frame
[self setNeedsLayout];
}
- (void)dealloc{
[[NSNotificationCenter defaultCenter]removeObserver:UITextViewTextDidChangeNotification];
}
- (void)awakeFromNib{
[super awakeFromNib];
self.backgroundColor= [UIColor clearColor];
UILabel *placeholderLabel = [[UILabel alloc]init];//添加一个占位label
placeholderLabel.font = [UIFont systemFontOfSize:14];
placeholderLabel.backgroundColor = [UIColor clearColor];
placeholderLabel.numberOfLines = 0; //设置可以输入多行文字时可以自动换行
[self addSubview:placeholderLabel];
self.placeholderLabel= placeholderLabel; //赋值保存
self.myPlaceholderColor= [UIColor lightGrayColor]; //设置占位文字默认颜色
self.font= [UIFont systemFontOfSize:14]; //设置默认的字体
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self]; //通知:监听文字的改变
}
以上是关于代码待封装的textview的主要内容,如果未能解决你的问题,请参考以下文章