当键盘出现在我的应用程序中时,按钮部分向上移动(仅按钮的文本移动)

时间:2016-11-27 15:09:15

标签: ios swift uistoryboard nslayoutconstraint uikeyboard

我的swift应用中有一个按钮位于屏幕底部。对它的限制是:

enter image description here

我还附加插座,用于将我的按钮与屏幕底部分开的约束:

enter image description here

当我运行应用程序时,我看到了我的按钮(我添加了一些背景颜色,以便我的示例清晰可见):

enter image description here

现在,奇怪的事情发生了 - 当键盘显示时,按钮上的文字向上移动,蓝色背景保持原样:

enter image description here

此外,按钮的可见部分根本无法点击。

是我的实施中的某种错误还是问题?

我的代码相当简单:

@IBOutlet weak var continueUsernameBottomConstraint: NSLayoutConstraint!

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


    NotificationCenter.default.addObserver(self, selector: #selector(tutorialKeyboardWillAppear), name: .UIKeyboardWillShow, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(tutorialKeyboardWillDisappear), name: .UIKeyboardWillHide, object: nil)

}


func tutorialKeyboardWillAppear(notification: NSNotification){
    print("KEYBOARD APPEARS")
    let endFrame = ((notification as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue

    continueUsernameBottomConstraint.constant = view.bounds.height - endFrame.origin.y

    self.view.layoutIfNeeded()
}

func tutorialKeyboardWillDisappear(notification: NSNotification){

    print("KEYBOARD DISAPPEARS")
    let endFrame = ((notification as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue

    continueUsernameBottomConstraint.constant = view.bounds.height - endFrame.origin.y

    self.view.layoutIfNeeded()

}

1 个答案:

答案 0 :(得分:2)

使用此

func tutorialKeyboardWillAppear(notification: NSNotification){
    print("KEYBOARD APPEARS")
    let endFrame = ((notification as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    continueUsernameBottomConstraint.constant = continueUsernameBottomConstraint.constant + CGFloat(endFrame.height)
    self.view.layoutIfNeeded()
}

func tutorialKeyboardWillDisappear(notification: NSNotification){

    print("KEYBOARD DISAPPEARS")
    let endFrame = ((notification as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    continueUsernameBottomConstraint.constant = continueUsernameBottomConstraint.constant -  CGFloat(endFrame.height)
    self.view.layoutIfNeeded()

}