gpt4 book ai didi

IOS 在应用程序启动时为 subview 设置动画?

转载 作者:可可西里 更新时间:2023-11-01 00:55:55 27 4
gpt4 key购买 nike

我只是想在一些 uiview 中设置动画,

  • 首先,我要在 viewWillAppear
  • 中移除屏幕边界之外的 subview
  • 然后我在 viewDidAppear
  • 中使用 UIView.animate 将它们移回原位

`

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
label.center.x -= view.bounds.width
username.center.x -= view.bounds.width
password.center.x -= view.bounds.width
login.center.x -= view.bounds.width
}

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("view did appear")
UIView.animate(withDuration: 1) {
self.label.center.x += self.view.bounds.width
self.username.center.x += self.view.bounds.width
self.password.center.x += self.view.bounds.width
self.login.center.x += self.view.bounds.width
}
}

我做错了什么?

编辑1

当我评论 viewDidAppear 时,它对 View 没有任何影响。 (他们在 Storyboard 中就位)

最佳答案

Aeid,如果可能的话,我想提供一个替代解决方案,让您无论是否有约束都可以设置动画。

分组

我注意到您正在移动 4 个 UI 元素。我可能建议您将它们全部组合到一个 UIView 中(具有清晰的背景颜色)。这样一来,您只需为一个 UI 元素设置动画。 One UIView

动画

我最喜欢的动画对象方法之一是“转换”它。您可以应用 3 种转换:

  1. 轮换
  2. 调整大小(称为“缩放”)
  3. 重新定位(称为“翻译”)

每个 UI 对象都有一个 .transform 属性。您使用 CGAffineTransform 应用转换。 (CG = Core Graphics,Affine = 保持平行关系。旋转、调整大小和重新定位不会扭曲或扭曲对象)

代码

class ViewController: UIViewController {

@IBOutlet weak var loginView: UIView!

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loginView.transform = CGAffineTransform(translationX: -view.bounds.width, y: 0)
}

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIView.animate(withDuration: 1) {
self.loginView.transform = .identity // Remove the transform
}
}
}

Animated Login

优势

  • 对象上有什么约束并不重要。它会起作用。
  • 您不必重新定位两次,只需一次。然后移除变换,让它回到原来的位置。

关于IOS 在应用程序启动时为 subview 设置动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48475972/

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