Swift - delay code execution: Unterschied zwischen den Versionen
Aus Wikizone
(Die Seite wurde neu angelegt: „== Links == Swift - Snippets how can i delay code execution for 0.2s in swift There are a few ways to delay code execution in Swift: Use the sleep f…“) |
(→Links) |
||
| Zeile 39: | Zeile 39: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
This method is similar to the DispatchQueue method, but it is specific to view controllers and uses a background thread to execute the delayed code. This method does not block the main thread and is suitable for use in production code. | This method is similar to the DispatchQueue method, but it is specific to view controllers and uses a background thread to execute the delayed code. This method does not block the main thread and is suitable for use in production code. | ||
| + | |||
| + | <syntaxhighlight lang="swift"> | ||
| + | sender.alpha = 0.5 | ||
| + | |||
| + | // Delay code execution for 0.2 seconds | ||
| + | perform(afterDelay: 0.2) { | ||
| + | // Code to be executed after the delay | ||
| + | sender.alpha = 1.0 | ||
| + | } | ||
| + | </syntaxhighlight> | ||
Version vom 28. Dezember 2022, 00:08 Uhr
Links
how can i delay code execution for 0.2s in swift
There are a few ways to delay code execution in Swift:
Use the sleep function from the sleep library:
import Foundation
// Delay code execution for 0.2 seconds
sleep(0.2)
This method is simple, but it is not recommended for use in production code because it blocks the main thread and can cause the user interface to become unresponsive.
Use the DispatchQueue class from the Dispatch library:
import Dispatch
// Delay code execution for 0.2 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
// Code to be executed after the delay
}
This method uses the main dispatch queue to asynchronously schedule the code to be executed after the specified delay. This method does not block the main thread and is suitable for use in production code.
Use the perform(inBackground:) method from the UIViewController class:
import UIKit
// Delay code execution for 0.2 seconds
perform(inBackground: {
Thread.sleep(forTimeInterval: 0.2)
}) {
// Code to be executed after the delay
}
This method is similar to the DispatchQueue method, but it is specific to view controllers and uses a background thread to execute the delayed code. This method does not block the main thread and is suitable for use in production code.
sender.alpha = 0.5
// Delay code execution for 0.2 seconds
perform(afterDelay: 0.2) {
// Code to be executed after the delay
sender.alpha = 1.0
}