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

时间:2017-08-01 13:53:22

标签: ios swift

我希望在应用启动时显示蓝色和黑色矩形。我写了这段代码。它的编译没有任何错误,但没有结果。

+----+-----------+----------+------------+  
| ID | Date_Time |  Event    | Control ID|  
+----+-----------+----------+------------+  
|  1 | 0/0/0     | Shutdown |            |  
|  2 | 0/0/0     | Start up |            |  
|  3 | 0/0/0     | Error    |            |  
|  4 | 0/0/0     | Info     |            |  
| 5  | 0/0/0     | Shutdown |            |  
| 6  | 0/0/0     | Error    |            |  
+----+-----------+----------+------------+  

+-------------------+----------+--------+-------+   
| Control ID        | Event    | Export | Flag  |
+-------------------+----------+--------+-------+  
| 1                 | Shutdown | TRUE   | TRUE  |  
| 2                 | Start up | TRUE   | FALSE |  
| 3                 | Error    | TRUE   | TRUE  |  
| 4                 | Info     | TRUE   | FALSE |  
+-------------------+----------+--------+-------+  

谁能告诉我哪里出错了?

提前致谢

1 个答案:

答案 0 :(得分:2)

永远不要在主线程上运行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()
}