Albin
Albin

Reputation: 145

Can't hide items within ToolbarItemGroup, disappears on iPhone

I have a view with a set of toolbar items where I sometimes want to hide some of the items when activating a certain state.

Consider the following SwiftUI code:

@State var hideToolbarItems = false

var body: some View {
    NavigationSplitView {
        Text("Hello, World!")
            .navigationTitle("MyToolbarItems")
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button {
                        hideToolbarItems.toggle()
                    } label: {
                        Text("Toggle")
                    }
                }
                ToolbarItemGroup(placement: .navigationBarTrailing) {
                    if !hideToolbarItems {
                        Button {
                        } label: {
                            Text("Button1")
                        }
                        Button {
                        } label: {
                            Text("Button2")
                        }
                        Button {
                        } label: {
                            Text("Button3")
                        }
                    }
                }
            }
    } detail: {
    }
}

When previewing this it seems to work as expected, the ToolbarItemGroup disappears when hideToolbarItems becomes true and appears again when hideToolbarItems is false. On an iPad device it works almost the same, the ToolbarItemGroup becomes grouped under a "..."-icon until the hideToolbarItems has changed back and forth, then it won't become grouped under a "..."-icon anymore. But the real problem is that the ToolbarItemGroup won't show at all on an iPhone device. Has anyone solved this problem on iPhone? I can't seem to find a good solution.

I am running Xcode 14.2 and use iOS 16.0.

Upvotes: 0

Views: 297

Answers (1)

noppe
noppe

Reputation: 85

SwiftUI effects different result by platforms. ToolbarItemGroup may be compact button only in iPad. if you want to show buttons as compact anytime, you can use Menu.

ToolbarItemGroup(placement: .navigationBarTrailing) {
    if !hideToolbarItems {
        Menu {
            Button {
            } label: {
                Text("Button1")
            }
            Button {
            } label: {
                Text("Button2")
            }
            Button {
            } label: {
                Text("Button3")
            }
        } label: {
            Image(systemName: "ellipsis.circle")
        }
    }
}

Upvotes: 1

Related Questions