gpt4 book ai didi

ios - 约束动画只会向上移动,不会向下移动

转载 作者:行者123 更新时间:2023-11-28 07:53:43 25 4
gpt4 key购买 nike

我有两个按钮可以在两个对象上触发动画——一个 View 和一个 ImageView ——它们的位置由自动布局设置。 (在尝试解决这个问题时,我将目的地简化为屏幕的顶部和底部。):

@objc func upButtonTapped() {
self.logo.centerYAnchor.constraint(equalTo: self.view.topAnchor, constant: 0).isActive = true
self.inputsView.bottomAnchor.constraint(equalTo: self.view.topAnchor, constant: 0).isActive = true
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
print("Up")
}
@objc func downButtonTapped() {
self.logo.centerYAnchor.constraint(equalTo: self.view.bottomAnchor, constant: 0).isActive = true
self.inputsView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: 0).isActive = true
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
print("Down")
}

upButtonTapped 动画可以正常工作,但 downButtonTapped 则不行。在与目的地玩了太久之后,我意识到 anchor 和约束的组合不会导致对象在屏幕上动画。这两个函数都由各自的按钮正确定位,我尝试将每个函数之间的约束更新交换为相同的结果。

如果有帮助,这里是我为两个对象设置的初始约束(使用自定义扩展):

logo.anchor(xCenter: view.centerXAnchor,
yCenter: view.topAnchor, yCenterConstant: view.frame.height / 3,
width: 65)
inputsView.anchor(bottom: view.safeAreaLayoutGuide.bottomAnchor, bottomConstant: -100,
xCenter: view.centerXAnchor,
width: view.frame.width * 0.7,
height: 200)

谁能告诉我发生了什么/如何解决?

最佳答案

我用单一 View 重现了您的结果。您的问题是您的 View 受到过度约束,因为您不断添加新的约束,但您从未删除它们。当 View 受到过度约束时,自动布局 通过选择要忽略的内容来打破约束。无论出于何种原因,它都支持“向上”约束。您需要有一个跟踪垂直约束的属性,并且需要在创建和激活新约束之前对该约束设置 isActive = false

这是我的例子的代码。我正在将单个红色方形 View 移动到屏幕的顶部和底部。请注意我如何使用一个属性来跟踪在垂直方向定位 View 的约束,以及我如何使用该属性来停用当前约束,然后存储并激活新约束。

class ViewController: UIViewController {

@IBOutlet weak var redView: UIView!

@IBOutlet weak var redCenter: NSLayoutConstraint!

var redCenterConstraint: NSLayoutConstraint?

override func viewDidLoad() {
super.viewDidLoad()

// start with the constraint set in the Storyboard
redCenterConstraint = redCenter
}

@IBAction func moveUp(_ sender: UIButton) {
// deactivate the current constraint
redCenterConstraint?.isActive = false

// create the new constraint
redCenterConstraint = redView.centerYAnchor.constraint(equalTo: self.view.topAnchor, constant: 0)

// activate the new constraint
redCenterConstraint?.isActive = true

// animate the change
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
}

@IBAction func moveDown(_ sender: UIButton) {
// deactivate the current constraint
redCenterConstraint?.isActive = false

// create the new constraint
redCenterConstraint = redView.centerYAnchor.constraint(equalTo: self.view.bottomAnchor, constant: 0)

// activate the new constraint
redCenterConstraint?.isActive = true

// animate the change
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
}
}

这里是在模拟器中运行:

enter image description here

关于ios - 约束动画只会向上移动,不会向下移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48938830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com