当键盘弹出时,我该如何将整个视图向上移动?(Swift)

6

enter image description here

底部的灰色框是一个文本视图。当我点击文本视图时,键盘会从底部弹出来。然而,弹出的键盘遮挡了文本视图。

为了在键盘弹出时将整个视图向上移动,我应该添加哪些功能?


1
请查看此链接 https://github.com/hackiftekhar/IQKeyboardManager - BoilingLime
谢谢@BoilingLime,它简单易用。 :-) - elvislkm
4个回答

2
为了检测键盘何时弹出,您可以监听NSNotificationCenter
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: “keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)

那将会调用 keyboardWillShowkeyboardWillHide。在这里,你可以对你的 UITextfield 做任何想做的事情。
func keyboardWillShow(notification: NSNotification) {
    if let userInfo = notification.userInfo {
        if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            //use keyboardSize.height to determine the height of the keyboard and set the height of your textfield accordingly
        }
    }
}

func keyboardWillHide(notification: NSNotification) {
    //pull everything down again
}

1

完整的Swift 4解决方案。

我在所有需要它的项目中使用它。

在viewWillAppear中注册以监听键盘的显示/隐藏,并使用下面的函数将视图向上移动和向下移动。

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

    subscribeToKeyboardNotifications()
}

// stop listening for changes when view is dissappearing
override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    unsubscribeFromKeyboardNotifications()
}

// listen for keyboard show/show events
func subscribeToKeyboardNotifications() {
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)
}

func unsubscribeFromKeyboardNotifications() {
    NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
}

@objc func keyboardWillHide(_ notification: Notification) {
    view.frame.origin.y = 0
}

在我的情况下,我有一个文本框位于底部,由于键盘的遮挡而被隐藏,因此如果正在使用,则将视图向上移动。
@objc func keyboardWillShow(_ notification: Notification) {
    if bottomTextField.isFirstResponder {
        view.frame.origin.y = -getKeyboardHeight(notification: notification)
    }
}

func getKeyboardHeight(notification: Notification) -> CGFloat {
    let userInfo = notification.userInfo
    let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
    return keyboardSize.cgRectValue.height
}

1
作为Milo所说,如果您想自己实现这个功能,您需要注册键盘显示/隐藏通知。
然后,您需要编写代码来确定键盘遮挡了屏幕的多少以及所讨论的字段位于屏幕的高度,以便您知道需要移动视图的量。
一旦完成,您需要根据您使用的是AutoLayout还是自动调整大小掩码(也称为“支架和弹簧”样式布局)来决定下一步操作。
我在开发者博客中写了一篇文章,其中包括用于移动键盘的工作代码。请参见此链接:

http://wareto.com/animating-shapes-using-cashapelayer-and-cabasicanimation

在那篇文章中,请查找底部标题为“滑动视图以为键盘腾出空间”的链接。

-1

Swift 4

这段代码不是很完美,但是值得一试!

首先将整个视图嵌入到scrollView中。

将以下可爱的小函数添加到您的类中:

@objc func keyboardNotification(_ notification: Notification) {
    if let userInfo = (notification as NSNotification).userInfo {
        let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
        let duration:TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
        let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
        let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions().rawValue
        let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)
        if (endFrame?.origin.y)! >= UIScreen.main.bounds.size.height {
            scrollViewBottomConstraint?.constant = 0
        } else {
            if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
                let keyboardHeight:Int = Int(keyboardSize.height)
                scrollViewBottomConstraint?.constant = CGFloat(keyboardHeight)
                scrollView.setContentOffset(CGPoint(x: 0, y: (scrollViewBottomConstraint?.constant)! / 2), animated: true)
            }
        }
        UIView.animate(withDuration: duration, delay: TimeInterval(0), options: animationCurve, animations: {
            self.view.layoutIfNeeded()
        }, completion: nil)
    }
}

.

将这个添加到您的ViewDidLoad中:
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardNotification(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)

不要忘记将你的scrollView的底部约束连接到你的类(名称为:“scrollViewBottomConstraint”)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接