【问题标题】:when a keyboard shows up in my app, the button partially moves up (only the text of the button moves)当我的应用程序中出现键盘时,按钮部分向上移动(仅按钮的文本移动)
【发布时间】:2017-04-11 08:31:39
【问题描述】:

我的swift 应用程序中有一个按钮,它位于屏幕底部。它的约束是:

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

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

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

而且按钮的可见部分根本不可点击。

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

我的代码很简单:

@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()

}

【问题讨论】:

  • continueUsernameBottomConstraint.constant = view.bounds.height - endFrame.origin.y 中的keyboardWillAppear 和消失对我来说都不好看。相反,如果您想在 keyboardWillAppear 中使用约束: continueUsernameBottomConstraint.constant = continueUsernameBottomConstraint.constant + keyBoardHeight 和 willDisappear continueUsernameBottomConstraint.constant = continueUsernameBottomConstraint.constant - keyBoardHeight。
  • Apple 首选的方式是在显示键盘的情况下使用 scrollView。或者在这种情况下,您甚至可以向上移动整个屏幕并将键盘附加到底部。

标签: ios swift uistoryboard nslayoutconstraint uikeyboard


【解决方案1】:

使用这个

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()

}

【讨论】:

  • 谢谢伙计,它现在起作用了,很奇怪为什么以前的方法不起作用,但是,如果有替代解决方案,我不会想太多为什么其他方法不起作用.. .
猜你喜欢
  • 1970-01-01
  • 2017-01-08
  • 1970-01-01
  • 2019-03-30
  • 2021-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-19
相关资源
最近更新 更多