Home > database >  Can't show dropdown menu over HStack in SwiftUI
Can't show dropdown menu over HStack in SwiftUI

Time:03-04

I have a list item that needs to have a dropdown menu that shows on top of the other views in the HStack.

This is what I have currently:

struct ListRow: View {
    @Binding var item: Item
    @State var showDropdown: Bool = false
    var body: some View {
        ZStack {
            HStack {
                VStack {
                    Text(item.name)
                        .fixedSize(horizontal: false, vertical: true)
                        .frame(maxWidth: .infinity, alignment: .topLeading)
                    ProgressView(value: item.percentDone)
                }.padding(.all, 10)
                Button(action: {
                    self.showDropdown.toggle()
                }, label: {
                    Image(systemName: "ellipsis.circle")
                }).buttonStyle(BorderlessButtonStyle())
                    .overlay (
                        VStack {
                            if self.showDropdown {
                                Spacer(minLength: 40)
                                Text("TEST")
                                    .onTapGesture {
                                        print("Delete")
                                    }
                            }
                        }.zIndex(10)
                    )
            }
        }
    }
}

But when I run it and click the button this is what I see

dropdown screenshot

It looks like the Text is not showing due to a view overflow/overlap with the rest of the HStack, but I thought that adding the .zIndex would place the dropdown on top of the rest of the views in the ZStack

CodePudding user response:

I figured out a better solution.

struct ListRow: View {
    @Binding var item: Item
    var body: some View {
        HStack {
            VStack {
                Text(item.name)
                    .fixedSize(horizontal: false, vertical: true)
                    .frame(maxWidth: .infinity, alignment: .topLeading)
                ProgressView(value: item.percentDone)
            }.padding(.all, 10)
            Menu {
                Button("Delete", action: {
                    print("Delete")
                })
            } label: {
                
            }
            .menuStyle(BorderlessButtonMenuStyle())
            .frame(width: 10, height: 10, alignment: .center)
        }
    }
}

CodePudding user response:

Just set frame for your overlay view to make it exceed its main view 's size

.overlay (
    VStack {
        if self.showDropdown {
            Spacer(minLength: 40)
            Text("TEST")
                .onTapGesture {
                    print("Delete")
                }
        }
    }.frame(width: 100)
)

Or you can try another approach like ZStack or Menu (as you mentioned a better solution)

  • Related