How to Wait in Objective-C and Swift

后端 未结 8 818
自闭症患者
自闭症患者 2021-01-31 02:22

I want to change my UILabel\'s text after 2 seconds.

I tried setting my UILabel\'s text to \"A text\", and use sleep(2) a

8条回答
  •  死守一世寂寞
    2021-01-31 02:57

    Grand Central Dispatch has a helper function dispatch_after() for performing operations after a delay that can be quite helpful. You can specify the amount of time to wait before execution, and the dispatch_queue_t instance to run on. You can use dispatch_get_main_queue() to execute on the main (UI) thread.

    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        // do something
    });
    

    In Swift 3, the above example can be written as:

    DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
        // do something
    }
    

提交回复
热议问题