Search code examples
macosbuttonswiftuilabelwidth

SwiftUI Button Text width violates borders, not compressed by HStack


I have a small HStack with Text and a Button. This is limited with maxWidth: 200

import SwiftUI

struct ContentView: View {
    var body: some View {
        HStack {
            Text("Some Text")
                .frame(maxWidth: .infinity)
            Button(action: {}, label: {
                Text("A Very much to long button Text with more Text")
                    .truncationMode(.middle)
            })
        }.frame(maxWidth: 200)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

This ends up scaling the button even beyond the borders of the HStack.

enter image description here

I do not want to hardcode a width with .frame(maxWidth: 50 on the Buttons Label Text. It should just take as much space as possible, after that truncating the text (.truncationMode)

How can this be done without GeometryReader so that the result looks like:

enter image description here

Update

As suggested, XCode is checked latest 13.2 on macOS 11.6


Solution

  • Seems to be related to known issues with macOS.

    Only solution is, to create a custom ButtonStyle and apply the necessary restrictions there:

    struct MacOSFixedButtonStyle: ButtonStyle {
        func makeBody(configuration: Self.Configuration) -> some View {
            configuration.label
                .truncationMode(.middle)
                .lineLimit(1)
        }
    }
    
    extension View {
        func fixedMacOSButton(
        ) -> some View {
            self.buttonStyle(
                MacOSFixedButtonStyle()
            )
        }
    }
    

    Applied via:

    Button("to long to read it and to put it in a view", action: {})
    .fixedMacOSButton()