简体   繁体   English

键盘出现时调整UITextView的大小

[英]Resize the UITextView when keyboard appears

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. 我有自动布局,因此使用了来自superview的textView-> bottom space的约束,并通过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;
  }];
}

The code above works perfect. 上面的代码非常完美。 What I don't understand is why I need to add +78 for iPhone6 or 183 for iPhone5. 我不明白为什么我需要为iPhone6添加+78或为iPhone5添加183。 These two values I came with trial and error. 这两个值我带来了反复试验。 If I don't add these, the textView extends below the keyboard. 如果我不添加这些,textView扩展到键盘下方。 Please help me solve this mystery. 请帮我解开这个谜。

In viewWillAppear method, add the following: viewWillAppear方法中,添加以下内容:

- (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);
}

And the other one like: 而另一个像:

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

    yourTextView.contentInset = UIEdgeInsetsZero;
}

It will work for all devices ;) 它适用于所有设备;)

Swift / Modified Version Swift /修改版

Using the above, I made some adjustments to use NSLayoutConstraint 's changing the height constant property when the keyboard shows and hides. 使用上面的内容,我做了一些调整,以便在键盘显示和隐藏时使用NSLayoutConstraint更改高度constant属性。 This also works if you rotate the device. 如果您旋转设备,这也适用。

1. Set up TextView Constraints 1.设置TextView约束

Then control drag an outlet from you height constraint to the class. 然后控制从您的高度约束拖出一个出口到该类。

在此输入图像描述

2. Add The Following 2.添加以下内容

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(SkillDescriptionViewController.keyboardWillShowHandle(_:)), name: UIKeyboardDidShowNotification, object: nil)

        NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(SkillDescriptionViewController.keyboardWillHideHandle), name: UIKeyboardWillHideNotification, object: nil)

    }


    func keyboardWillShowHandle(note:NSNotification) {
        guard let keyboardRect = note.userInfo![UIKeyboardFrameEndUserInfoKey] as? NSValue else { return }
        let kbFrame = keyboardRect.CGRectValue()
        tvHeight.constant = -kbFrame.height
        view.layoutIfNeeded()
    }

    func keyboardWillHideHandle() {
        tvHeight.constant = 0
        view.layoutIfNeeded()
    }

Swift 5 solution based on answers above 基于以上答案的Swift 5解决方案

Notification API has changed (20190707) as well as how to use #selector Notification API已更改(20190707)以及如何使用#selector

The solution here can be used when the keyboard pop covers UITextView which causes user unable to see the text been edited. 当键盘pop覆盖UITextView导致用户无法看到已编辑的文本时,可以使用此处的解决方案。

import UIKit

class DCNodeLogEntryViewController: UIViewController {
    @IBOutlet weak var textViewNodeLogEntry: UITextView!

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        NotificationCenter.default.addObserver(
            self,
            selector: #selector(DCNodeLogEntryViewController.handleKeyboardDidShow(notification:)),
            name: UIResponder.keyboardDidShowNotification,
            object: nil
        )

        NotificationCenter.default.addObserver(
            self,
            selector: #selector(DCNodeLogEntryViewController.handleKeybolardWillHide),
            name: UIResponder.keyboardWillHideNotification,
            object: nil
        )
    }

    @objc func handleKeyboardDidShow(notification: NSNotification) {
        guard let keyboardRect = notification
            .userInfo![UIResponder.keyboardFrameEndUserInfoKey]
            as? NSValue else { return }

        let frameKeyboard = keyboardRect.cgRectValue

        textViewNodeLogEntry.contentInset = UIEdgeInsets(
            top: 0.0,
            left: 0.0,
            bottom: frameKeyboard.size.height,
            right: 0.0
        )

        view.layoutIfNeeded()
    }

    @objc func handleKeybolardWillHide() {
        textViewNodeLogEntry.contentInset = .zero
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM