gpt4 book ai didi

ios - 如何在 Swift 的 ViewDidAppear 中运行循环?

转载 作者:行者123 更新时间:2023-11-28 12:19:05 25 4
gpt4 key购买 nike

我想在应用程序启动时交替显示一个蓝色和黑色的矩形。我写了这段代码。它编译正常没有任何错误,但没有结果。

import UIKit

class ViewController: UIViewController {

var mybool = true

override func viewDidAppear(_ animated: Bool) {


while(mybool){
let firstFrame = CGRect(x: 160, y: 240, width: 100, height: 150)
let firstView = UIView(frame: firstFrame)
firstView.backgroundColor = UIColor.blue
view.addSubview(firstView)

let secondView = UIView(frame: firstFrame)
secondView.backgroundColor = UIColor.black
view.addSubview(secondView)

}
}


}

谁能告诉我哪里出错了?

提前致谢

最佳答案

永远不要在等待主线程上的属性更改时运行 while!这是您的整个 UI 所依赖的线程。该应用程序看起来像是崩溃了,iOS 迟早会杀死它。

使用核心动画:

weak var loadingView: UIView!
override func viewDidLoad() {
super.viewDidLoad()

let frame = CGRect(x: 160, y: 240, width: 100, height: 150)
let subview = UIView(frame: frame)
subview.backgroundColor = .black
self.view.addSubview(subview)

UIView.animate(withDuration: 1, delay: 0, options: [.autoreverse, .repeat, .curveEaseInOut], animations: {
subview.backgroundColor = .blue
}, completion: nil)

self.loadingView = subview
}

当你想停止动画时(例如,当加载完成时):

func stopAnimation() {
loadingView.layer.removeAllAnimations()
}

关于ios - 如何在 Swift 的 ViewDidAppear 中运行循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45439838/

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