admin管理员组

文章数量:1422017

I'm having issues getting SwiftUI's Menu working in a toolbar. When outside a toolbar it works fine, but when in a toolbar pressing the menu's button doesn't open the sub menu. I've reported to apple as FB16853917.

Anyone find a workaround?

Minimal reproduction:

import SwiftUI

struct MyMenu: View {
    var body: some View {
        Menu("Test Menu") {
            Button {
                print("action 1")
            } label: {
                Text("Sub 1")
            }
            Button {
                print("action 2")
            } label: {
                Text("Sub 2")
            }
        }
    }
}

struct ContentView: View {
    var body: some View {
        NavigationStack {
            VStack {
                MyMenu()
            }
            .padding()
            .toolbar {
                MyMenu()
            }
        }
    }
}

I'm having issues getting SwiftUI's Menu working in a toolbar. When outside a toolbar it works fine, but when in a toolbar pressing the menu's button doesn't open the sub menu. I've reported to apple as FB16853917.

Anyone find a workaround?

Minimal reproduction:

import SwiftUI

struct MyMenu: View {
    var body: some View {
        Menu("Test Menu") {
            Button {
                print("action 1")
            } label: {
                Text("Sub 1")
            }
            Button {
                print("action 2")
            } label: {
                Text("Sub 2")
            }
        }
    }
}

struct ContentView: View {
    var body: some View {
        NavigationStack {
            VStack {
                MyMenu()
            }
            .padding()
            .toolbar {
                MyMenu()
            }
        }
    }
}
Share Improve this question asked Mar 13 at 15:18 Cameron LittleCameron Little 3,74927 silver badges38 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

It works if you use placement .principal for the toolbar item. However, the menu is then shown in the middle, instead of being on the right.

If you don't have any other toolbar items that are blocking the way, the menu can be pushed to the right side by applying .frame(maxWidth: .infinity, alignment: .trailing):

.toolbar {
    ToolbarItem(placement: .principal) {
        MyMenu()
            .frame(maxWidth: .infinity, alignment: .trailing)
    }
}

本文标签: tvOS SwiftUI Menu in toolbarStack Overflow