Last active
June 12, 2019 08:39
-
-
Save enzosterro/8a632bfeb7157a24b7d8b113a593bafb to your computer and use it in GitHub Desktop.
How to update a single child view in SwiftUI?
This file contains 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
class CustomColor: BindableObject { | |
var didChange = PassthroughSubject<CustomColor, Never>() | |
let id = UUID() | |
var color: Color { | |
didSet { | |
self.didChange.send(self) | |
} | |
} | |
init(color: Color) { | |
self.color = color | |
} | |
func change(toColor color: Color) { | |
self.color = color | |
} | |
} | |
class ColorStore: BindableObject { | |
var didChange = PassthroughSubject<ColorStore, Never>() | |
var colors: [CustomColor] = [] { | |
didSet { | |
didChange.send(self) | |
} | |
} | |
init() { | |
(0...10).forEach { _ in colors.append(CustomColor(color: .red)) } | |
} | |
} | |
struct ContentView: View { | |
@ObjectBinding var colorStore: ColorStore | |
var body: some View { | |
NavigationView { | |
List(colorStore.colors) { color in | |
ColorShape(color: color) | |
} | |
.navigationBarTitle(Text("Colors")) | |
.navigationBarItems(trailing: | |
Button(action: { self.colorStore.colors.append(CustomColor(color: .green)) }) { | |
Text("Add") | |
}) | |
} | |
} | |
} | |
struct ColorShape: View { | |
@ObjectBinding var color: CustomColor | |
var body: some View { | |
Button(action: { self.color.change(toColor: .blue) }, label: { | |
ShapeView(shape: Circle(), style: color.color) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment