Created
June 22, 2022 04:37
-
-
Save pteasima/49433d9c6cc8444b14bce1f54e57410a to your computer and use it in GitHub Desktop.
SwiftUI OnDestroy modifier
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
private struct OnDestroy: ViewModifier { | |
let onDestroy: () -> Void | |
final class Lifetime { | |
var onDestroy: () -> Void = { } | |
deinit { onDestroy() } | |
} | |
@State var lifetime: Lifetime = .init() | |
func body(content: Content) -> some View { | |
lifetime.onDestroy = onDestroy | |
return content | |
.background(Color.clear) //this needs to be actually different than content itself, else `body(content:)` wont even run (thanks to SwiftUI magic) | |
} | |
} | |
extension View { | |
func onDestroy(_ onDestroy: @escaping () -> Void) -> some View { | |
self.modifier(OnDestroy(onDestroy: onDestroy)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment