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-2025
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16277441.html
未经授权禁止转载,违者必究!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
2021-05-16 饺子(水饺),馄饨,抄手 All In One
2020-05-16 TweenMax & GSAP & SVG Animation
2020-05-16 vue-parent-child-lifecycle-order All In One
2020-05-16 react-parent-child-lifecycle-order
2020-05-16 React LifeCycle API All In One
2020-05-16 Serverless & FaaS
2020-05-16 JavaScript & Design Patterns All In One