gpt4 book ai didi

ios - 在 Swift 的导航栏中动画更改图像

转载 作者:行者123 更新时间:2023-11-28 14:04:12 27 4
gpt4 key购买 nike

我在 Storyboard 中创建的 ViewController 的导航栏中有一个图像和图像的 outlet 属性,我想为到另一个图像的过渡设置动画。 View Controller 使用转换以模态方式启动。

我可以通过更改其 alpha 值来动画化图像的淡入淡出。但是,如果我更改图像而不是淡入淡出,则没有动画。相反,新图像在页面加载后立即可见。无论我将动画代码放在 viewDidLoad 还是 viewWillAppear 中都是如此。我希望这个动画只在 View 加载时发生一次,但是,我在 viewWillAppear 中尝试了它只是为了看看我是否可以获得效果。

这是我的代码

// in viewdidload or viewwillappear
let newImage = UIImage(named: "headshot.png")
UIView.transition(with: self.imageView,
duration:0.5,
options: .transitionCrossDissolve,
animations: { self.ImageView.image = newImage },
completion: nil)

相对于常规 View ,导航栏中的动画图像有什么特别之处吗?或者我需要做些什么来为导航栏中的图像变化设置动画?

最佳答案

你的图像没有动画的原因是因为从编译器的角度来看,用另一个图像替换另一个图像(就像插入图像一样)是一个原子 Action 。这意味着 self.ImageView.image = newImage 是一步中发生的一行。也就是说,在任何时间点,您的 imageView 要么将 newImage 作为其 image 属性,要么没有。像这样以原子方式发生的状态变化不能随着时间的推移而变化。

另一种看待它的方式是,为了将动画的持续时间更改为 0.5 秒(而不是在单个步骤中自动执行此操作),XCode 编译器必须按字面意思在 0.5 秒内将图像零碎地放入 imageView 中。显然,这是未定义的行为。编译器如何知道在什么时间将图像的哪些部分放在屏幕上?

您的问题的一个简单解决方案是将两个单独的 imageView(其中一个开始时是透明的)放置在屏幕上完全相同的位置。每个 imageView 都有一个单独的图像,您可以通过简单地淡出一个图像然后淡入另一个图像来在这两个图像之间进行转换,如下所示:

class viewController: UIViewController {
let imageView1 = UIImageView("headshot1.png")
let imageView2 = UIImageView("headshot2.png")

override viewDidLoad() {
super.viewDidLoad()

/* add imageViews to your view and place them both
in the middle of the screen */
imageView1.translatesAutoresizingMaskIntoConstraints = false
imageView1.alpha = 1.0
self.addSubview(imageView1)

/* notice that this imageView is completely transparent */
imageView2.translatesAutoresizingMaskIntoConstraints = false
imageView2.alpha = 0.0
self.addSubview(imageView2)

/* place both imageViews in the middle of your screen,
with imageView1 completely visible and imageView2
completely transparent */
imageView1.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
imageView1.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true

imageView2.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
imageView2.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true

// fade out first imageView
UIView.animate(withDuration: 0.25) {
imageView1.alpha = 0.0
}

// fade in second imageView
UIView.animate(withDuration: 0.25) {
imageView2.alpha = 1.0
}
}
}

您也可以使用您的 transition 函数代替我的 animate 函数 - 逻辑几乎相同。

关于ios - 在 Swift 的导航栏中动画更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53188181/

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