【问题标题】:Animating constraint to push UIView above Keyboard issue [duplicate]将 UIView 推送到键盘问题上方的动画约束 [重复]
【发布时间】:2018-11-13 16:20:38
【问题描述】:

我有这个CommentViewController。它嵌入在容器视图中。在这个CommentViewController 中,有一个UITableView 用于显示cmets,UIView 包含一个UITextField 和一个UIButton。包含这两个对象的UIView 通过自动布局在底部、右侧和左侧固定到安全区域,顶部到UITableView

现在,当用户点击UITextField 时,整个视图(包括按钮和文本字段在内)应该被提升到键盘上方。我正在尝试为视图的底部约束设置动画,但它不起作用。

这是代码:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

}

@objc func keyboardWillShow(_ notification: NSNotification) {
    let keyboardFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue
    UIView.animate(withDuration: 0.3) {
        self.textFieldViewBottomConstraint.constant = keyboardFrame!.height
    }
}

这是故事板:

这是点击文本字段后的结果。

PS:当我点击UITextField 时,控制台会显示以下消息:

2018-06-04 14:11:52.471848+0300 AppName[91846:8829073] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/d/Library/Developer/CoreSimulator/Devices/C89347A2-1598-4F31-BBAC-1F98F970A248/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles 2018-06-04 14:11:52.472588+0300 Shippers[91846:8829073] [MC] Reading from private effective user settings.

【问题讨论】:

标签: swift uiview nslayoutconstraint uiviewanimation nsnotificationcenter


【解决方案1】:

更改约束的常量后需要调用self.view.layoutIfNeeded()

self.textFieldViewBottomConstraint.constant = keyboardFrame!.height
   UIView.animate(withDuration: 0.3) {
    self.view.layoutIfNeeded()
}

//

 NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)

编辑:

为底部约束设置常量属性取决于哪个元素是约束中的第一个元素,所以如果约束看起来像这样

这里是第一个文本字段

textfield_Bottom = view_Bottom * 乘数 + 常数。 —> 然后 常数必须为负,因为当 Y 轴向上时,我们会减少 想要在显示键盘时使视图上升

这里是第一个视图

view_Bottom = textfield_Bottom * 乘数 + 常数。 —> 然后 常数必须是加号

【讨论】:

  • 试试 UIKeyboardDidShow
  • 你能说得具体一点吗?
  • 很遗憾,没有。再次,没有结果。问题可能是这个CommentViewController 实际上在容器视图中吗?此外,当我点击 UITextField 时,控制台会显示此消息:(请参阅我的更新答案)
  • 你能在函数内部打印任何东西来看看它是否运行
  • 是的,我也怀疑该函数没有被调用,但确实如此。我看到了打印的声明
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-22
  • 1970-01-01
  • 2018-05-30
  • 1970-01-01
相关资源
最近更新 更多