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];
    
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值