Skip to content

Instantly share code, notes, and snippets.

@adam-zethraeus
Created September 22, 2023 10:58
Show Gist options
  • Save adam-zethraeus/cb9b750be7caebd3e9457e4bb9c31d11 to your computer and use it in GitHub Desktop.
Save adam-zethraeus/cb9b750be7caebd3e9457e4bb9c31d11 to your computer and use it in GitHub Desktop.
WithState — easy state in Xcode previews
import SwiftUI
extension View {
public func withState<Value, V: View>(_ state: Value, @ViewBuilder content: @escaping (_ state: Binding<Value>) -> V) -> some View {
modifier(WithStateModifier(state, content: content))
}
}
public struct WithState<Value, V: View>: View {
public init(_ value: Value, @ViewBuilder content builder: @escaping (_ state: Binding<Value>) -> V) {
self.value = value
self.builder = builder
}
private let value: Value
private let builder: (_ state: Binding<Value>) -> V
public var body: some View {
withState(value, content: builder)
}
}
struct WithStateModifier<Value, V: View>: ViewModifier {
init(_ state: Value, @ViewBuilder content builder: @escaping (_ state: Binding<Value>) -> V) {
_state = .init(wrappedValue: state)
self.builder = builder
}
@State var state: Value
private let builder: (_ state: Binding<Value>) -> V
@MainActor func body(content: Content) -> V {
return builder(.init(projectedValue: $state))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment