【问题标题】:swift keyboard moves up twice快速键盘向上移动两次
【发布时间】:2015-12-22 12:39:36
【问题描述】:

当键盘出现时,我使用以下代码向上移动视图。 这很好用,但我有一个问题,如果我点击一个文本字段并直接点击下一个文本字段,它会将我的视图向上移动两次。
我怎样才能让它只向上移动一次视图?

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

func keyboardWillShow(notification: NSNotification) {
     print(self.view.frame.origin.y)


    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {

        self.view.frame.origin.y -= keyboardSize.height

    }

    print(self.view.frame.origin.y)
}

func keyboardWillHide(notification: NSNotification) {
    print("is dissapaering now")
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {

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

【问题讨论】:

  • 我个人建议使用约束,而不是绝对值。另外我会使用子视图而不是向上移动整个视图。

标签: ios swift view keyboard


【解决方案1】:

听起来您应该在再次显示之前检查键盘是否已经显示。创建一个新的 Bool 变量来跟踪状态并仅在 Bool 值为 false 时移动视图。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-07
    • 2017-01-08
    • 1970-01-01
    • 2017-01-29
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    相关资源
    最近更新 更多