Skip to content

Instantly share code, notes, and snippets.

@pteasima
Created June 22, 2022 04:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pteasima/49433d9c6cc8444b14bce1f54e57410a to your computer and use it in GitHub Desktop.
Save pteasima/49433d9c6cc8444b14bce1f54e57410a to your computer and use it in GitHub Desktop.
SwiftUI OnDestroy modifier
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