Skip to content

Instantly share code, notes, and snippets.

@samalone
Created October 23, 2023 18:01
Show Gist options
  • Save samalone/d1d0d8cd9cb4258a7fc7593f55c0fc98 to your computer and use it in GitHub Desktop.
Save samalone/d1d0d8cd9cb4258a7fc7593f55c0fc98 to your computer and use it in GitHub Desktop.
Getting a SwiftUI Binding to an Environment object property
import SwiftUI
@Observable class Account {
var name: String = "Foo"
}
// What is the right way to get a Binding to a property of an Environment object?
struct AccountEditor: View {
@Environment(Account.self) var account
var body: some View {
TextField("Name", text: $account.name) // Error: Cannot find '$account' in scope
}
}
@divadretlaw
Copy link

@Observable class Account {
    var name: String = "Foo"
}

struct AccountEditor: View {
    @Environment(Account.self) var account
    
    var body: some View {
        @Bindable var account = account
        TextField("Name", text: $account.name)
    }
}

See https://developer.apple.com/documentation/swiftui/bindable

@samalone
Copy link
Author

That's it, thanks! I knew about @Bindable, but had no idea it could be used on a local var.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment