Search code examples
swiftuiswiftui-link

Why are my SwiftUI Links not respecting frame maxWidth?


I am trying to make a list of buttons/links that all have the same width, regardless of text content. Unfortunately, it seems like the Link() items do not respect the .frame(maxWidth) settings and just do whatever they want. I cannot find any resources online that describe how to do this, so I am turning here to see if anyone can help me determine the best way to line these up to be the same width.

My code below:

VStack(alignment: .center) {
                Button {
                    bypass.toggle()
                } label: {
                    Text("Push to Bypass")
                    .frame(maxWidth: .infinity)
                }
                .font(.title2)
                .fontWeight(.bold)
                .buttonStyle(.borderedProminent)
                .foregroundColor(Color(hue: 1.0, saturation: 1.0, brightness: 1.0, opacity: 0.825))
                .tint(Color(red: 0.005, green: 0.669, blue: 0.791))
                Link("Settings", destination: URL(string: "http://192.168.10.1/TSettings")!)
                    .frame(maxWidth: .infinity)
                    .font(.title2)
                    .fontWeight(.bold)
                    .buttonStyle(.borderedProminent)
                    .foregroundColor(.white)
                    .tint(Color(red: 0.005, green: 0.669, blue: 0.791))
                Link("Recorder Settings", destination: URL(string: "http://192.168.10.1/VB")!)
                    .frame(maxWidth: .infinity)
                    .font(.title2)
                    .fontWeight(.bold)
                    .buttonStyle(.borderedProminent)
                    .foregroundColor(.white)
                    .tint(Color(red: 0.005, green: 0.669, blue: 0.791))
                Link("Download Data", destination: URL(string: "http://192.168.10.1/ddownload")!)
                    .frame(maxWidth: .infinity)
                    .font(.title2)
                    .fontWeight(.bold)
                    .buttonStyle(.borderedProminent)
                    .foregroundColor(.white)
                    .tint(Color(red: 0.005, green: 0.669, blue: 0.791))
                Link("Download Audio", destination: URL(string: "http://192.168.10.1/generate")!)
                    .frame(maxWidth: .infinity)
                    .font(.title2)
                    .fontWeight(.bold)
                    .buttonStyle(.borderedProminent)
                    .foregroundColor(.white)
                    .tint(Color(red: 0.005, green: 0.669, blue: 0.791))
            }.fixedSize(horizontal: true, vertical: false)

What it currently looks like:

Preview of Code


Solution

  • Add this to your struct:

    @Environment(\.openURL) var openURL
    

    Use a regular button and apply the desired modifiers:

    Button {
        openURL(URL(string: "http://192.168.10.1/TSettings")!)
    } label: {
        Text("Settings")
            .frame(maxWidth: .infinity)
    }