iOS键盘隐藏UITextField

时间:2019-04-11 19:24:00

标签: swift uitextfield uikeyboard

当我按下屏幕下部的UITextField时,它会被键盘隐藏。 我想做的是使用标准的iOS动画向上移动视图,以达到UITextField插入文本的位置。 我正在使用 Swift 5 (Xcode 10.2)

开发应用程序

我得到的结果是,现在我可以移动视图了(比期望的要早一点),但是每次我按下UITextField时,视图都会移动,而不仅仅是被菜单项隐藏的视图。键盘。

class ViewController: UIViewController {
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    @objc func keyboardWillShow(notification: NSNotification) {
        guard let userInfo = notification.userInfo else {
            return
        }

        guard let keyboardSize = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
            return
        }

        let keyboardFrame = keyboardSize.cgRectValue

        if self.view.frame.origin.y == 0 {
            self.view.frame.origin.y -= keyboardFrame.height
        }
    }

    @objc func keyboardWillHide(notification: NSNotification) {
        guard let userInfo = notification.userInfo else {
            return
        }

        guard let keyboardSize = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
            return
        }

        let keyboardFrame = keyboardSize.cgRectValue

        if self.view.frame.origin.y != 0 {
            self.view.frame.origin.y += keyboardFrame.height
        }
    }
}

我想要获得的结果是,如果用户按下将被键盘隐藏的UITextField,那么在键盘出现后不久,视图就会向上移动,直到用户可以看到按下的UITextField

我一直在寻找解决这个问题的方法,但是我看到的所有其他方法似乎都已经过时或没有尽我所能实现。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用scrollview:

import UIKit

class ViewController: UIViewController {

    @IBOutlet var scrollView: UIScrollView!


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        NotificationCenter.default.addObserver(self,selector:#selector(self.keyboardWillShow),name:UIResponder.keyboardDidShowNotification, object: nil)
        NotificationCenter.default.addObserver(self,selector: #selector(self.keyboardWillHide),name:UIResponder.keyboardDidHideNotification, object: nil)

    }

    @objc func keyboardWillShow(notification: Notification) {

        guard let userInfo = notification.userInfo,

            let frame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
            else{
                return

        }

        let contentInset = UIEdgeInsets(top: 0, left: 0, bottom: frame.height, right: 0)

        scrollView.contentInset = contentInset

    }

    @objc func keyboardWillHide(notification: Notification)

    {
        scrollView.contentInset = UIEdgeInsets.zero
    }

}