Swift & SwiftUI delay code All In One
Swift & SwiftUI delay code All In One
solutions
DispatchQueue.main.asyncAfter
.onAppear() {
/*
*/
self.animate = false;
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
// ✅
self.animate = true;
// self.animate.toggle();
// print("Async after 1 seconds");
}
// self.animate.toggle();
// self.animate = false;
// sleep(UInt32(1.0));
// self.animate = true;
// sleep(1.0);
// Cannot convert value of type 'Double' to expected argument type 'UInt32'
// Replace '1.0' with 'UInt32(1.0)'
// delay
// Text("").task(self.delay);
// Converting non-sendable function value to '@Sendable () async -> Void' may introduce data races
// Result of call to 'task(priority:_:)' is unused
// self.delay();
// ❌ 'async' call in a function that does not support concurrency
}
.onDisappear() {
// self.animate.toggle();
// self.animate = false;
}
print("Before delay")
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
print("Async after 2 seconds")
}
print("Before delay")
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) {
print("async after 500 milliseconds")
}
task
struct ContentView: View {
@State private var hasTimeElapsed = false
var body: some View {
Text(hasTimeElapsed ? "Sorry, too late." : "Please enter above.")
.task(delayText)
}
private func delayText() async {
// Delay of 7.5 seconds (1 second = 1_000_000_000 nanoseconds)
try? await Task.sleep(nanoseconds: 7_500_000_000)
hasTimeElapsed = true
}
}
perform
perform(#selector(authenticate), with: nil, afterDelay: 1)
sleep
print("Before delay")
sleep(1.0)
print("After delayed")
refs
https://programmingwithswift.com/how-to-add-a-delay-to-code-in-swift/
https://stackoverflow.com/questions/59682446/how-to-trigger-action-after-x-seconds-in-swiftui
https://www.zerotoappstore.com/create-a-delay-or-wait-in-swift.html
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16277441.html
未经授权禁止转载,违者必究!