xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

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.hackingwithswift.com/example-code/system/how-to-run-code-after-a-delay-using-asyncafter-and-perform

https://www.zerotoappstore.com/create-a-delay-or-wait-in-swift.html



©xgqfrms 2012-2025

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @   xgqfrms  阅读(103)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 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
点击右上角即可分享
微信分享提示