【问题标题】:Specific function runs at the same moment on all of the views. How can I make it run one after the other?特定功能在所有视图上同时运行。我怎样才能让它一个接一个地运行?
【发布时间】:2019-06-30 10:30:01
【问题描述】:

我正在使用 SwiftUI 构建 Simon Says 应用程序,并且在构建它时遇到了一个错误。 问题在于我在下面键入的一个特定功能。 此函数设置 Simon Says 按钮的 alphas(只是一个简单的按钮动画)并将它们设置回 0.5。我希望它在每个视图上同时运行一个,因为到目前为止动画同时在所有按钮上运行。

我们将不胜感激!

for index in settings.guessArray {
            wait(time: 2.0) {
                settings.alphas[index] = 1.0
                wait(time: 0.3) {
                    settings.alphas[index] = 0.5
                }
            }
        }

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    也许这样的事情会起作用......

    等待是异步执行的,因此请增加每个按钮的初始等待时间以及时将它们分开:

    var offset = 0.0
    for index in settings.guessArray {
        wait(time: 2.0 + offset) {
            settings.alphas[index] = 1.0
            wait(time: 0.3) {
                settings.alphas[index] = 0.5
            }
        }
    
        // increase this value to increase the spacing between the buttons
        // lighting up
        offset += 0.3
    }
    
    //if you're using this function on multiple SwiftUI views at the same time
    //consider placing the offset variable in @EnvironmentObject.
    

    【讨论】:

    • 谢谢!那肯定奏效了。虽然我必须将此值分配给 @EnvirnomentObject 以便它可以全局读取并全局递增,因为它同时在所有视图上运行!
    【解决方案2】:

    我在这里盲目飞行,但你用信号量实现了这一点。改编自以下代码:

    let semaphore = DispatchSemaphore(value: 0)
    
    for index in settings.guessArray {
        semaphore.wait() // When animation on one button begins
        wait(time: 2.0) {
            settings.alphas[index] = 1.0
            wait(time: 0.3) {
                settings.alphas[index] = 0.5
                semaphore.signal() // When animation on a button finishes
            }
        }
    }
    

    【讨论】:

    • 感谢您的回答,但遗憾的是不是这样。按钮仍然同时亮起。但我不得不使用 DispatchSemaphore(value: 1) 因为某种原因值 0 阻止了按钮的动画。
    猜你喜欢
    • 1970-01-01
    • 2015-02-23
    • 2021-05-27
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    相关资源
    最近更新 更多