我们如何让键盘出现在 swift 中的 textView 下方?

How do we make keyboard appear below textView in swift?

我使用

完成了出现在文本字段下方的键盘

在 View 上确实加载了一个 observer()

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

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Gold_Loan_First_ViewController.keyboardWillBeHidden(_:)), name: UIKeyboardWillHideNotification, object: nil)

然后更新框架

weak var activeField: UITextField?

func textFieldDidEndEditing(textField: UITextField) {
    self.activeField = nil


}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField==txtOTP {
        txtOTP.errorMessage=""
    }
  return true
}
func textFieldDidBeginEditing(textField: UITextField) {
    self.activeField = textField

}




func keyboardDidShow(notification: NSNotification)
{
    if let activeField = self.activeField,
        let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height, right: 0.0)
        self.scrollView.contentInset = contentInsets
        self.scrollView.scrollIndicatorInsets = contentInsets
        var aRect = self.view.frame
        aRect.size.height -= keyboardSize.size.height
        if (!CGRectContainsPoint(aRect, activeField.frame.origin)) {
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }


}

func keyboardWillBeHidden(notification: NSNotification)
{
    let contentInsets = UIEdgeInsetsZero
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
}

但是我该如何为 textView 做这件事。我用 textView 的 didBeginEditing 尝试了相同的代码,但没有任何积极效果

一种简单且无需代码的解决方案是在您的应用中使用以下 pods。

IQKeyboardManger

稍后您只需将其导入 App Delegate 并在 didfinishLaunching 方法中添加这两行代码:

  IQKeyboardManager.sharedManager().enable = true

您的问题将在整个应用程序中得到解决。

对于 Swift 5:

IQKeyboardManager.shared.enable = true

我遇到过这样的情况。首先,我在 UiViewController 中添加了扩展名:

    extension CCViewController : UITextViewDelegate {
        func textViewDidBeginEditing(_ textView: UITextView) {
            // write code as per your requirements
        }

        func textViewDidEndEditing(_ textView: UITextView) {
             // write code as per your requirements
        }

        func textViewDidChange(_ textView: UITextView) {
            self.p_adjustMessageFieldFrameForTextView(textView)
        }
    }

    // Defining the p_adjustMessageFieldFrameForTextView method

    fileprivate func p_adjustMessageFieldFrameForTextView(_ textView : UITextView) {
            var finalheight : CGFloat = textView.contentSize.height + 10
            var kMaxMessageFieldHeight : CGFloat = 50
            if  (finalheight > kMaxMessageFieldHeight) {
                finalheight = kMaxMessageFieldHeight;
            } else if (finalheight < kCommentTextViewHeight){
                finalheight = kCommentTextViewHeight;
            }

            scrollView!.view.frame = CGRect(x: 0, y: kNavBarHeight + statuBarHeight, width: SCREEN_WIDTH,height: SCREEN_HEIGHT - finalheight - keyboardRect!.size.height - kNavBarHeight - statuBarHeight)
// It is there for understanding that we have to calculate the exact frame of scroll view

            commentTextView!.frame = CGRect(x: 0, y: bottomOfView(scrollView!.view), width: SCREEN_WIDTH, height: finalheight)
            self.p_setContentOffsetWhenKeyboardIsVisible()
        }

    // Defining the p_setContentOffsetWhenKeyboardIsVisible method

    fileprivate func p_setContentOffsetWhenKeyboardIsVisible() {
            // here you can set the offset of your scroll view
        }

还有一个名为bottomView()的方法:

func bottomOfView(_ view : UIView) -> CGFloat {
        return view.frame.origin.y + view.frame.size.height
    }

Salman Ghumsani 是对的。

请将UIKeyboardFrameBeginUserInfoKey改为UIKeyboardFrameEndUserInfoKey

Apple Debeloper 文档:键盘通知用户信息键

UIKeyboardFrameEndUserInfoKey

包含 CGRect 的 NSValue 对象的键,该 CGRect 在屏幕坐标中标识键盘的 ending 框架矩形。框架矩形反映了设备的当前方向。

UIKeyboardFrameBeginUserInfoKey

一个键 NS值 包含一个对象 CG矩形 在屏幕坐标中标识键盘的 starting 框架矩形。框架矩形反映了设备的当前方向。

结论

因此,如果您使用 UIKeyboardFrameBeginUserInfoKey,您可能会将键盘高度设为 0。导致系统认为UITextView没有被覆盖

找到正确的键盘高度并将其分配给textView的底部约束或减少textView的y位置。 喜欢:

第一步: 在你 viewController.

中创建一个 属性 keyboardHeight

var keyboardHeight: CGFloat = 0.0

Step-2:使textView的底部约束@IBOutlet

@IBOutlet weak var textViewBottomConstraint: NSLayoutConstraint!

第 3 步:

fileprivate func addKeyboardNotification() {
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

fileprivate func removeKeyboardNotification() {
    IQKeyboardManager.shared().isEnabled = true
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

将这些函数复制并粘贴到您的视图控制器,然后在 viewDidLoad() 和您 viewController

中调用 self.addKeyboardNotification()

第四步:

deinit {
    self.removeKeyboardNotification()
}

还将此代码添加到您的 viewController。

第五步:

    func keyboardWillShow(_ notification: Notification) {
    if let keboardFrame = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue, self.keyboardHeight <= 0.0 {
        self.keyboardHeight = keboardFrame.height + 45.0 //(Add 45 if your keyboard have toolBar if not then remove it)
    }

    UIView.animate(withDuration: 0.3, animations: {
        self.textViewBottomConstraint.constant = self.keyboardHeight
    }, completion: { (success) in
    })
}

func keyboardWillHide(_ notification: Notification) {
    UIView.animate(withDuration: 0.3, animations: {
        self.textViewBottomConstraint.constant = 0.0
    }, completion: { (success) in
    })
}

通过键盘管理textView就是这样了。 如果你不想使用 textViewBottomConstraint 你可以使用 textView 的 y 位置。

您可以通过桥接 Header 简单地使用 TPKAScrollViewController.h & TPKAScrollViewController.m 个文件。

将这些 objective-C 文件拖到您的 swift 项目时,它会自动要求创建桥接。创建桥接 Header 并将 #import "TPKAScrollViewController.h" 导入 YourApp-Bridging-Header.h 文件。

之后,只需 select XIB 中的 scrollView 并将其 class 更改为 TPKeyboardAvoidingScrollView,如下所示。