出现键盘时约束未更新 [英] Constraints Not Updating When Keyboard Appears

查看:69
本文介绍了出现键盘时约束未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am making a sign up screen and would like to update a few top anchors so that when the keyboard appears, the top anchor constant decreases and the keyboard doesn't cover any text fields.

我创建了一个topConstant变量:

I have created a topConstant variable:

var constraintConstant: CGFloat = 35

并按照以下步骤设置我的观点:

And have set up my views as follows:

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

然后我编写了这段代码:

Then I have written this code:

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

我不确定为什么有害对象没有更新.有什么想法吗?

I'n not sure why the constriants aren't updating. Any ideas?

推荐答案

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

Ok. I had this problem when i first started out on iOS with Swift. See the problem is with your understanding of anchors.

您指定的常数不能像您期望的那样起作用. (您期望它的作用类似于某种侦听器,该侦听器将根据变量值的更新不断进行更新.它不是).它将仅在设置时获取变量的值,然后不再显示返回,除非您访问该锚点并手动更改常数.

The constant that you specify doesn't function like how you are expecting it to. (You are expecting it to function like some kind of listener which will keep updating based on the update in the value of the variable. It doesn't) It will just take the value of the variable at the time of setting and then not look back unless you access that anchor and change the constant manually.

这就是为什么您必须存储锚的实例并像这样每年更改常量的原因.

Which is why you have to store the instance of the anchor and change the constant maually like this.

定义约束变量:

var topAnchorConstraint: NSLayoutConstraint!

将适当的约束存储在变量中

Store the appropriate constraint in the variable

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

现在,您需要根据需要更改常数.

Now you need to change the constant as required.

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

    }, completion: nil)
}

这篇关于出现键盘时约束未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆