gpt4 book ai didi

ios - 如何将 View 动画化到 X 和 Y 的中心?

转载 作者:行者123 更新时间:2023-11-28 10:34:50 26 4
gpt4 key购买 nike

我有一个 ImageView,它对 Helper Header View 有 centerX 和 centerY 约束,如下图所示

enter image description here

我想将该 Logo imageView 设置为位于屏幕中央的动画,如下图所示: enter image description here

我已经尝试了一些代码,但它不起作用,老实说,我不确定下面的这段代码,这是我尝试的。也许你有更好的方法。这是我试过的

首先,我尝试为两个约束提供标识符: enter image description here enter image description here

然后我删除约束并创建一个新的约束,如下面的代码:

 UIView.animate(withDuration: 1.1, delay: 0.5, usingSpringWithDamping:  0.4, initialSpringVelocity: 0.0, animations: {

// remove the initial constraint
self.mainLogoCenterXConstraint.isActive = false
self.mainLogoCenterYConstraint.isActive = false

// create new constraint
let newMainLogoCenterXConstraint = NSLayoutConstraint(
item: self.mainLogoImageView,
attribute: .centerX,
relatedBy: .equal,
toItem: self.view,
attribute: .centerY,
multiplier: 1.0,
constant: 0)
newMainLogoCenterXConstraint.identifier = "mainLogoCenterXConstraint"
newMainLogoCenterXConstraint.isActive = true

let newMainLogoCenterYConstraint = NSLayoutConstraint(
item: self.mainLogoImageView,
attribute: .centerY,
relatedBy: .equal,
toItem: self.view,
attribute: .centerY,
multiplier: 1.0,
constant: 0)
newMainLogoCenterYConstraint.identifier = "mainLogoCenterYConstraint"
newMainLogoCenterYConstraint.isActive = true


self.view.layoutIfNeeded()

}, completion: nil)

但它崩溃并给出错误:

'NSInvalidLayoutConstraintException', reason: 'Constraint improperly relates anchors of incompatible types:

也许您有更好的方法来实现这一目标....

最佳答案

您在创建与 self.mainLogoImageView.centerXself.view.centerY 相关的第一个约束时出错 - 将第二个约束更改为 self.view .centerX。您不能将 x 轴 anchor 绑定(bind)到 y 轴 anchor 。

此外,请确保正确设置动画,查看我关于如何使用自动布局执行此操作的回答 here .

在你的情况下:

// remove the initial constraint
self.mainLogoCenterXConstraint.isActive = false
self.mainLogoCenterYConstraint.isActive = false

// create new constraint
let newMainLogoCenterXConstraint = NSLayoutConstraint(
item: self.mainLogoImageView,
attribute: .centerX,
relatedBy: .equal,
toItem: self.view,
attribute: .centerX,
multiplier: 1.0,
constant: 0)
newMainLogoCenterXConstraint.identifier = "mainLogoCenterXConstraint"
newMainLogoCenterXConstraint.isActive = true

let newMainLogoCenterYConstraint = NSLayoutConstraint(
item: self.mainLogoImageView,
attribute: .centerY,
relatedBy: .equal,
toItem: self.view,
attribute: .centerY,
multiplier: 1.0,
constant: 0)
newMainLogoCenterYConstraint.identifier = "mainLogoCenterYConstraint"
newMainLogoCenterYConstraint.isActive = true

self.view.setNeedsLayout()

UIView.animate(withDuration: 1.1, delay: 0.5, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.0, animations: {

self.view.layoutIfNeeded()

}, completion: nil)

关于ios - 如何将 View 动画化到 X 和 Y 的中心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54107008/

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