Anton
Anton

Reputation: 3257

SwiftUI Menu breaks layout

This sample SwiftUI app (Xcode 12.5.1) consists of a Menu and a button. Tapping the button toggles the title of the menu between "Short Text" and "Much Longer Text".

Unfortunately, the layout does not perform correctly. As you can see, the "Much Longer Text" is needlessly truncated. But once the menu title is tapped and the menu briefly appears, the title grows to its proper (untruncated) size and the problem disappears:

enter image description here

Here is the code:

struct ContentView: View {
    @State private var textIsLong = false

    var body: some View {
        VStack {
            Menu {
                Text("Menu Item")
            } label: {
                Text(textIsLong ? "Much Longer Text" : "Short Text")
            }
            .font(.system(size: 30))
            .foregroundColor(Color(UIColor.label))
            .lineLimit(1)

            Button("Toggle Title", action: { textIsLong.toggle()})
        }
    }
}

In contrast, replacing the menu with Text(textIsLong ? "Much Longer Text" : "Short Text") eliminates the problem; the text is never truncated.

Is this just a SwiftUI layout bug? Either way, can you think of a workaround?

Upvotes: 5

Views: 1728

Answers (1)

Visal Rajapakse
Visal Rajapakse

Reputation: 2042

You can fix this by setting the .frame() of the Text in the Menu label to the following to resolve the truncation and layout break

Menu {
    Text("Menu Item")
} label: {
    Text(textIsLong ? "Much Longer Text" : "Short Text")
        .frame(maxWidth: .infinity)  // making maxWidth infinity 
}

Upvotes: 6

Related Questions