出现键盘时调整UITextView的大小 [英] Resize the UITextView when keyboard appears

查看:43
本文介绍了出现键盘时调整UITextView的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在键盘出现时调整文本视图的大小.我的代码如下.我启用了自动布局,因此使用了SuperView的textView->底部空间约束,并通过IBOutlet distanceFromBottom引用了它.

I want to resize the text view when the keyboard appears. The code I have is below. I have auto layout on, hence using a constraint of textView->bottom space from superview and referencing it via IBOutlet distanceFromBottom.

- (void)keyboardWillShow:(NSNotification *)notification
{
  [UIView animateWithDuration:0.3 animations:^{
    NSDictionary* d = [notification userInfo];
    CGRect r = [d[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    r = [textView convertRect:r fromView:Nil];
    if(IS_IPHONE_6||IS_IPHONE_6P)
      distanceFromBottom.constant = r.origin.y+78;
    else if(IS_IPHONE_5)
      distanceFromBottom.constant = r.origin.y+183;
  }];
}

上面的代码很完美.我不明白的是为什么我需要为iPhone6添加+78或为iPhone5添加183.这两个值是我反复尝试得出的.如果我不添加这些内容,则textView会扩展到键盘下方.请帮助我解决这个谜.

The code above works perfect. What I don't understand is why I need to add +78 for iPhone6 or 183 for iPhone5. These two values I came with trial and error. If I don't add these, the textView extends below the keyboard. Please help me solve this mystery.

推荐答案

viewWillAppear 方法中,添加以下内容:

In viewWillAppear method, add the following:

- (void) viewWillAppear:(BOOL)paramAnimated{
    [super viewWillAppear:paramAnimated];

    [[NSNotificationCenter defaultCenter] 
        addObserver:self 
           selector:@selector(handleKeyboardDidShow:) 
               name:UIKeyboardDidShowNotification object:nil];

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

然后实现通知中心的两种方法,如下所示:

Then implement the two methods of the notification center, like this:

- (void) handleKeyboardDidShow:(NSNotification *)paramNotification{

    NSValue *keyboardRectAsObject =
        [[paramNotification userInfo] 
            objectForKey:UIKeyboardFrameEndUserInfoKey];

    CGRect keyboardRect = CGRectZero;
    [keyboardRectAsObject getValue:&keyboardRect];

    yourTextView.contentInset =
        UIEdgeInsetsMake(0.0f,
                         0.0f,
                         keyboardRect.size.height,
                         0.0f);
}

另一个像:

- (void) handleKeyboardWillHide:(NSNotification *)paramNotification{

    yourTextView.contentInset = UIEdgeInsetsZero;
}

它将适用于所有设备;)

It will work for all devices ;)

这篇关于出现键盘时调整UITextView的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆