如何在不冻结UI的情况下延迟for循环

问题描述 投票:0回答:1

我目前正在使用排序可视化工具,但是我需要for循环来“运行得更慢”,因为我想慢慢地可视化算法的工作方式,例如气泡排序。

这是我的代码

    func bubbleSort(array: inout [Rectangle], view: UIView) {
    for i in 1 ... array.count {
        for j in 0 ..< array.count - i {
            changeRectColor(rect: array[j])
            changeRectColor(rect: array[j+1])

            Thread.sleep(forTimeInterval: 1)


            if (array[j].height > array[j+1].height){
                sortRectColor(rect: array[j])
                sortRectColor(rect: array[j+1])
                Thread.sleep(forTimeInterval: 1)

                rectGenerator.removeRectangleView(view: view, tag: array[j].rectView.tag)
                rectGenerator.removeRectangleView(view: view, tag: array[j+1].rectView.tag)

                let temp = array[j].xPos
                array[j].xPos = array[j+1].xPos
                array[j+1].xPos = temp

                rectGenerator.regenerateRectangleView(rect: &array[j], view: view)
                rectGenerator.regenerateRectangleView(rect: &array[j+1], view: view)


                array.swapAt(j, j+1)
            }

            returnRectColor(rect: array[j])
            returnRectColor(rect: array[j+1])

            Thread.sleep(forTimeInterval: 1)   
        }
    }
}

但是如果执行此操作,sleep()将冻结UI,并且不会显示该过程。

如何执行类似的操作但又不冻结UI?

swift for-loop freeze
1个回答
0
投票

您可以使用定时器e.x延迟1秒

var counter = 0
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
   guard counter < array.count else { timer.invalidate() ; return }
   // do job
   counter += 1
 }
© www.soinside.com 2019 - 2024. All rights reserved.