输入框根据文字多少自动改变高度

类似微信聊天输入框,当文字换行时,自动增加输入框高度,此高度有个最大值限制
  //先定义屏幕宽高

 #define kScreenWidth [UIScreen mainScreen].bounds.size.width
 #define kScreenHeight [UIScreen mainScreen].bounds.size.height

@property(nonatomic,weak)UIView *bgView;
@property(nonatomic,weak)UITextView *textView;
@property(nonatomic,weak)UIButton *sendBtn;
@property(nonatomic, assign) CGFloat bgViewY;
@property(nonatomic, assign) NSInteger rows;


- (void)viewDidLoad {
    [super viewDidLoad];

    _rows = 1;

    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, kScreenHeight - 60, kScreenWidth, 60)];
    bgView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:bgView];
    self.bgView = bgView;

    UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(10, 10, kScreenWidth - 70, 30)];
    textView.delegate = self;
    textView.font = [UIFont systemFontOfSize:15];
    [bgView addSubview:textView];
    self.textView = textView;

    UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sendBtn.frame = CGRectMake(kScreenWidth - 50, 10, 40, 30);
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [bgView addSubview:sendBtn];
    self.sendBtn = sendBtn;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];  
}

- (void)textViewDidChange:(UITextView *)textView{
    // numberlines用来控制输入的行数
    NSInteger numberLines = textView.contentSize.height / textView.font.lineHeight;
    if (numberLines != _rows) {
        _rows = numberLines;
    
        if (_rows < 7) {
            [self changeFrame:textView.contentSize.height];
        }else{
            self.textView.scrollEnabled = YES;
        }
        [textView setContentOffset:CGPointZero animated:YES];
    }
}
- (void)changeFrame:(CGFloat)height{
    //改变bgView的高度、Y
    CGRect originalFrame = self.bgView.frame;
    originalFrame.size.height = 30 + height;
    originalFrame.origin.y = _bgViewY - height + 30;

    //改变textView的高度
    CGRect textViewFrame = self.textView.frame;
    textViewFrame.size.height = height;

    [UIView animateWithDuration:0.3 animations:^{
        self.bgView.frame = originalFrame;
        self.textView.frame = textViewFrame;
    }];  
}

- (void)keyboardChangeFrame:(NSNotification *)note {
    CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
    float duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey]floatValue];
    [UIView animateWithDuration:duration animations:^{
        self.bgView.transform = CGAffineTransformMakeTranslation(0, keyboardFrame.origin.y - kScreenHeight);
        _bgViewY = self.bgView.frame.origin.y;
    }];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

你可能感兴趣的:(输入框根据文字多少自动改变高度)