【问题标题】:Constraints Not Updating When Keyboard Appears出现键盘时约束不更新
【发布时间】:2018-08-27 15:06:03
【问题描述】:

我正在制作一个注册屏幕,并想更新一些顶部锚点,以便当键盘出现时,顶部锚点常数减小并且键盘不覆盖任何文本字段。

我创建了一个 topConstant 变量:

var constraintConstant: CGFloat = 35

我的观点如下:

view.addSubview(passwordTextField)
passwordTextField.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 25).isActive = true
passwordTextField.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -25).isActive = true
passwordTextField.heightAnchor.constraint(equalToConstant: 50).isActive = true
passwordTextField.topAnchor.constraint(equalTo: emailTextField.bottomAnchor, constant: constraintConstant).isActive = true

然后我写了这段代码:

func textFieldDidBeginEditing(_ textField: UITextField) {
    constraintConstant = 15
    view.layoutIfNeeded()
}

我不确定为什么约束不更新。有什么想法吗?

【问题讨论】:

    标签: ios swift autolayout nslayoutconstraint


    【解决方案1】:

    好的。当我第一次使用 Swift 在 iOS 上开始时,我遇到了这个问题。看到问题在于您对锚点的理解。

    您指定的常量与您期望的不同。 (您期望它像某种侦听器一样运行,它将根据变量值的更新不断更新。它不会)它只会在设置时获取变量的值,然后不看除非您访问该锚点并手动更改常量。

    这就是为什么你必须像这样存储锚的实例并更改常量。

    定义约束变量:

    var topAnchorConstraint: NSLayoutConstraint!
    

    在变量中存储适当的约束

    topAnchorConstraint = passwordTextField.topAnchor.constraint(equalTo: emailTextField.bottomAnchor, constant: 35)
    topAnchorConstraint.isActive = true
    

    现在您需要根据需要更改常量。

    func textFieldDidBeginEditing(_ textField: UITextField) {
        UIView.animate(withDuration: 1.0, animations: {
            self.topAnchorConstraint.constant = 15
            self.view.layoutIfNeeded()
    
        }, completion: nil)
    }
    

    【讨论】:

    • 工作就像一个魅力。谢谢!
    • @Rakesha Shastri 这不是重复的
    • @Sh_Khan 不,你的似乎没有任何解释。
    • @LukeRoberts 请将其他答案标记为已接受。我只是为它添加了一个解释,并通过添加一个动画块来增加一点优雅。
    • @RakeshaShastri 我不需要正确的检查,我想提醒您网站政策至少在一个答案的范围内而不是其他重复项
    【解决方案2】:

    你需要

    var topCon:NSLayoutConstraint!
    

    //

    topCon = passwordTextField.topAnchor.constraint(equalTo: emailTextField.bottomAnchor, constant: constraintConstant)
    topCon.isActive = true
    

    //

    func textFieldDidBeginEditing(_ textField: UITextField) {
        topCon.constant = 15
        view.layoutIfNeeded()
    }
    

    【讨论】:

      猜你喜欢
      • 2018-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-05
      • 2018-12-04
      相关资源
      最近更新 更多