IM模块--UItextView带有placeholder属性,自动调节高度
参考资料:
[简书地址](http://www.jianshu.com/users/23d0ae412e19/latest_articles)
#import <UIKit/UIKit.h>
@interface MessageInputView : UITextView
@property (nonatomic,copy) void (^UpdateTextFrame)(CGFloat th) ;
@end
#import "MessageInputView.h"
@interface MessageInputView()<UITextViewDelegate>
@property (nonatomic,strong) UILabel *placeholderLabel;
@end
@implementation MessageInputView
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
[self setUpUi];
}
return self;
}
- (void)setUpUi{
_placeholderLabel = [[UILabel alloc]init];
_placeholderLabel.font = [UIFont systemFontOfSize:15];
_placeholderLabel.text = @"请输入";
_placeholderLabel.textColor = [UIColor lightGrayColor];
[self addSubview:_placeholderLabel];
self.layer.cornerRadius = 6;
self.layer.masksToBounds = YES;
self.delegate = self;
self.showsHorizontalScrollIndicator = NO;
self.showsVerticalScrollIndicator = NO;
self.scrollEnabled = NO;
// 文本有改动的时候通知 ---
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textViewChange) name:UITextViewTextDidChangeNotification object:nil];
}
- (void)layoutSubviews{
[super layoutSubviews];
_placeholderLabel.frame = CGRectMake(5, 0, self.bounds.size.width, self.bounds.size.height);
}
- (void)textViewChange{
if (self.text.length == 0) {
_placeholderLabel.hidden = NO;
}else{
_placeholderLabel.hidden = YES;
}
}
#pragma mark UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView{
// 获取当前 TextView的高度
CGFloat tH = [textView sizeThatFits:textView.frame.size].height;
NSLog(@"%f",tH);
// 修改高度
if (self.UpdateTextFrame != nil) {
self.UpdateTextFrame(tH);
}
}
@end
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor grayColor];
MessageInputView *messageView = [[MessageInputView alloc]initWithFrame:CGRectMake(50, 400, 100, 30)];
__block MessageInputView *blockSelf = messageView;
[messageView setUpdateTextFrame:^(CGFloat th) {
[UIView animateWithDuration:0.2 animations:^{
blockSelf.frame = CGRectMake(50, 400, 100, th);
}];
}];
[self.view addSubview:messageView];
}
还没有评论,来说两句吧...