Here is my WatchOS app test. I've only tested in the simulator in 11.3.1 (Deployment Target 6.1) and 11.4 beta (Deployment Target 6.2)
import SwiftUI
private final class Foo: ObservableObject {
@Published var bar = Color.green
}
struct FilledButton: ButtonStyle {
// this do not work, runtime error when this is referenced, see below, works fine with ViewModifier
@EnvironmentObject fileprivate var foo: Foo
func makeBody(configuration: Configuration) -> some View {
configuration.label
.foregroundColor(configuration.isPressed ? .red : .white)
.padding()
.background(Color.accentColor)
.padding()
// Thread 1: Fatal error: No ObservableObject of type Foo found. A View.environmentObject(_:) for Foo may be missing as an ancestor of this view.
.background(self.foo.bar) // <==== runtime error anytime you reference this
.cornerRadius(8)
}
}
struct ContentView: View {
var body: some View {
AppView()
.accentColor(.orange)
.buttonStyle(FilledButton())
.environmentObject(Foo()) // <=== @EnvironmentObject is set here, this works with ViewModifier, not ButtonStyle
}
}
struct AppView: View {
var body: some View {
VStack(spacing: 5) {
Text("Hi, I'm Paul!")
Keypad()
}
}
}
struct Keypad: View {
var body: some View {
VStack(spacing: 5) {
Button(action: {}) { Text("One") }
Button(action: {}) { Text("Two") }
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}