xcode 中的简单淡入功能

simple fade in function in xcode

尽管我尽了最大的努力,但我在帧淡入时间的代码上还是失败了。由于某种我无法理解的原因, withDuration 根本没有消失。 如果有人有时间查看我的代码,我将非常感谢您的帮助...

import UIKit
import PlaygroundSupport


let view = UIView(frame: CGRect(x: 128, y: 128, width: 256, height: 256))
view.backgroundColor = .red
UIView.animate(withDuration: 3) {
view.alpha = 1
}

let containerView =  UIView(frame: CGRect(x: 0, y: 0, width: 512, height: 
512))
containerView.backgroundColor = .white
PlaygroundPage.current.liveView = containerView
containerView.addSubview(view)

问题 1:view.alpha 已经是 1,所以没有任何动画。

问题 2:顺序很重要。事情按照你命令的顺序发生。这个顺序一定要连贯。

所以:

let containerView =  UIView(frame: CGRect(x: 0, y: 0, width: 512, height: 512))
containerView.backgroundColor = .white
PlaygroundPage.current.liveView = containerView
let view = UIView(frame: CGRect(x: 128, y: 128, width: 256, height: 256))
view.alpha = 0
view.backgroundColor = .red
containerView.addSubview(view)
UIView.animate(withDuration: 3) {
    view.alpha = 1
}