当键盘快速显示时移动按钮

时间:2016-08-31 15:32:14

标签: swift

在UIViewController中,我有几个文本字段,一个按钮位于UIViewController的底部。 对于按钮,我设置了一个常量为0的底部约束。 然后我从底部约束到UIViewController做了一个出口。

当我运行代码时,按钮不会向上移动。我已经看到了关于stackoverflow的建议,我应该添加UIScrollView,但这意味着,我必须删除UIViewController上的所有对象,放置UIScrollView,然后再次将我的对象放在UIVIewController上。

   @IBOutlet weak var bottomConstraint: NSLayoutConstraint!    

    // When tapping outside of the keyboard, close the keyboard down
       override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    self.view.endEditing(true)
}

// Stop Editing on Return Key Tap. textField parameter refers to any textfield within the view

       func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}



// when keyboard is about to show assign the height of the keyboard to bottomConstraint.constant of our button so that it will move up

     func keyboardWillShow(notification: NSNotification) {
if let userInfo = notification.userInfo {
    if let keyboardSize: CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {

        bottomConstraint.constant = keyboardSize.size.height
        view.setNeedsLayout()
     }

   }
 }

  // When keyboard is hidden, move the button to the bottom of the view
func keyboardWillHide(notification: NSNotification) {
    bottomConstraint.constant = 0.0
    view.setNeedsLayout()
}

enter image description here

5 个答案:

答案 0 :(得分:7)

解决这个问题的典型方法是使用以下代码移动键盘:

ViewController类中的

  func keyboardWillShow(notification: NSNotification) {

        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            if view.frame.origin.y == 0{
                let height = keyboardSize.height

                self.view.frame.origin.y += height
            }

        }

    }

    func keyboardWillHide(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            if view.frame.origin.y != 0 {
                let height = keyboardSize.height
                self.view.frame.origin.y -= height
            }

        }
    }
ViewDidLoad方法中的

 NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
 NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)

请阅读本文: 不允许您尝试解决问题的方式。在上面的代码中,如果您将view更改为按钮变量名称,按钮将会向上拍摄然后再向下。这是因为自动布局和程序布局无法一起使用,它是一个或另一个。解决这个问题的方法是通过编程方式创建该按钮(使用CGRect),然后使用上面的代码在键盘按下时仅移动该按钮。 (通过将view更改为按钮变量名来执行此操作。

  func keyboardWillShow(notification: NSNotification) {

        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            if view.frame.origin.y == 0{
                let height = keyboardSize.height

                self.myButton.frame.origin.y += height
            }

        }

    }

    func keyboardWillHide(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            if view.frame.origin.y != 0 {
                let height = keyboardSize.height
                self.myButton.frame.origin.y -= height
            }

        }
    }

要以编程方式创建按钮,您将使用与此类似的代码:

myButton.frame = CGRect(...)

答案 1 :(得分:3)

您需要添加(viewDidLoad)观察员来调用您的函数:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillShow), name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillHide), name: UIKeyboardDidHideNotification, object: nil)

答案 2 :(得分:1)

对上面 Ryan 的回答的补充,这可以通过自动布局完成,不需要框架和 CGRect。

Swift 5

在您的视图中,像往常一样约束按钮,但在键盘隐藏/显示时添加对约束的引用以进行修改:

var bottomButtonConstraint = NSLayoutConstraint()

bottomButtonConstraint = yourButton.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor, constant: -12)
bottomButtonConstraint.isActive = true

在您的 ViewController 的 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)

也在你的 ViewController 中:

@objc private func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        self.yourCustomView.bottomButtonConstraint.constant -= keyboardSize.height
    }
}

@objc private func keyboardWillHide(notification: NSNotification) {
    self.yourCustomView.bottomButtonConstraint.constant = -12
}

答案 3 :(得分:0)

考虑使用这个 pod:https://cocoapods.org/pods/IQKeyboardManager 在 AppDelegate.swift 中,只需导入 IQKeyboardManagerSwift 框架并启用 IQKeyboardManager。

导入 IQKeyboardManagerSwift

@UIApplicationMain 类 AppDelegate:UIResponder、UIApplicationDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

  IQKeyboardManager.shared.enable = true

  return true
}

}

答案 4 :(得分:-1)

您可以使用此扩展名:

extension UIView {

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

    @objc func keyboardWillShow(notification: NSNotification) {

        if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
                let height = keyboardSize.height
                self.frame.origin.y -= height

        }

    }
    @objc
    func keyboardWillHide(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
                let height = keyboardSize.height
                self.frame.origin.y += height


        }
    }
}

并仅将其用于一个视图,而不是所有子视图:

    override func viewDidLoad() {
        super.viewDidLoad()
        submitBtn.setKeyboardShowObserver()
    }

并向上移动所有子视图:

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.setKeyboardShowObserver()
    }