Home > Blockchain >  SwiftUI View wrapped up in Menu doesn't resize
SwiftUI View wrapped up in Menu doesn't resize

Time:05-01

I want to use View inside Menu and my View has @State property, but I faced the problem that view wrapped up in Menu doesn't resize. I checked documentation and didn't found nothing that can affect on view size inside Menu. Can somebody describe why Menu have this behavior and how to solve this moment?

import SwiftUI

struct MenuView: View {

@State var greeting: Greetings = .short

enum Greetings: String, Identifiable, CaseIterable {
    case short = "Hi"
    case medium = "Hello"
    case long = "Nice to see you"
    
    var id: String { self.rawValue }
}

var body: some View {
    VStack(spacing: 20) {
        Picker("Options", selection: $greeting) {
            ForEach(Greetings.allCases) { greeting in
                Text(greeting.rawValue).tag(greeting)
            }
        }
        .pickerStyle(.segmented)
        Text("Greeting wrapped in menu:")
        Menu {
            Button("Send to Someone", action: {})
            Button("Save as PDF", action: {})
        } label: {
            Label(greeting.rawValue, systemImage: "doc.fill")
                .labelStyle(.titleOnly)
        }
        
        Text("Greeting without menu:")
        Text(greeting.rawValue)
    }
}
}

CodePudding user response:

I am assuming that you mean the text within the Menu Label is not growing or shrinking depending on which selection you make in the Picker.

This is because the size of the label is being set but not being changed. If you're okay with it, setting a maxWidth of .infinity on the frame of the Label gives you this capability.

Label(greeting.rawValue, systemImage: "doc.fill")
    .labelStyle(.titleOnly)
    .frame(maxWidth: .infinity) <<-- This here

showcasing the frame example

  • Related