UITextView的使用以及打开键盘的时候自动调整UITextView的位置

1,UITextview使用键盘上得return按钮进行退出键盘,限制输入个数;

2,使用UIKeyboardWillShowNotification通知,进行监控键盘是否弹出,根据键盘的高度,自动调整UItextView的高度,实现动画效果.原理比较简单,直接上代码.哈哈大笑


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

    //退出键盘

    if ([text isEqualToString:@"\n"]) {

        [textView resignFirstResponder];

        return NO;

    }

    

    //限制字数为300

    if (range.location >= 300 ) {

        return NO; // return NO to not change text

    }

    

    return YES;

}


- (void)keyboardWillShow:(NSNotification *)notification {

    

    NSDictionary *userInfo = [notification userInfo];

    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];

    CGRect keyboardRect = [aValue CGRectValue];

    CGFloat keyboardTop = keyboardRect.origin.y;

    

    // Get the duration of the animation.

    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];

    NSTimeInterval animationDuration;

    [animationDurationValue getValue:&animationDuration];

    

    // Animate the resize of the text view's frame in sync with the keyboard's appearance.

    [UIView beginAnimations:nil context:NULL];

    [UIView setAnimationDuration:animationDuration];

    

    CGFloat newViewY = keyboardTop - _resuseReasonView.frame.size.height;

    _resuseReasonView.frame = CGRectMake(_resuseReasonView.frame.origin.x, newViewY, _resuseReasonView.frame.size.width, _resuseReasonView.frame.size.height);

    

    [UIView commitAnimations];

}


- (void)keyboardWillHide:(NSNotification *)notification {

    

    NSDictionary *userInfo = [notification userInfo];

    

    // Get the duration of the animation.

    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];

    NSTimeInterval animationDuration;

    [animationDurationValue getValue:&animationDuration];

    

    // Animate the resize of the text view's frame in sync with the keyboard's appearance.

    [UIView beginAnimations:nil context:NULL];

    [UIView setAnimationDuration:animationDuration];

    

    CGFloat resuseReasonViewX = 15;

    CGFloat resuseReasonViewH = kScreenHeight / 2;

    CGFloat resuseReasonViewY = (kScreenHeight - resuseReasonViewH) / 2;

    CGFloat resuseReasonViewW = kScreenWidth - resuseReasonViewX * 2;

    _resuseReasonView.frame = CGRectMake(resuseReasonViewX, resuseReasonViewY, resuseReasonViewW, resuseReasonViewH);

    

    [UIView commitAnimations];

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值