This code, which displays a toolbar button to toggle the "bookmarked" property of a model object, works as intended in an iPhone simulator running iOS 16.0:
class Item: ObservableObject {
@Published var bookmarked = false
}
struct ContentView: View {
@StateObject var item = Item()
var body: some View {
NavigationView {
Text(self.item.bookmarked.description)
.toolbar {
MyToolbar(item: self.item)
} //.toolbar
} //NavigationView
} //body
} //ContentView
struct MyToolbar: ToolbarContent {
@ObservedObject var item: Item
var body: some ToolbarContent {
ToolbarItem {
Button {
self.item.bookmarked.toggle()
} label: {
Image(systemName: "bookmark")
.symbolVariant(self.item.bookmarked ? .fill : .none)
.foregroundColor(.yellow)
} //Button
} //ToolbarItem
} //body
} //MyToolbar
In an iOS 15.0 simulator, however, the bookmark image in the toolbar fails to change between filled and empty (even though the underlying model value toggles correctly).
Am I using the .toolbar modifier incorrectly for iOS 15.0 code?
Edit: Incidentally, if I use the ToolbarItem {...}
code directly in ContentView
under the .toolbar
modifier, then it works. But I would like to keep this code in an external ToolbarContent
struct, if possible.