如何使用 SwiftUI 扩展按钮的宽度

How to extend the width of a button using SwiftUI

我不知道如何在 SwiftUI 中更改按钮的宽度。

我已经尝试过: 使用 .frame(minWidth: 0, maxWidth: .infinity), 在按钮和导航链接周围使用 Spacer(), 使用文本字段上的框架和按钮上的填充,查看文档,以及我在网上搜索时发现的其他一些东西。然而,没有任何改变按钮的宽度。

NavigationLink(destination: Home(), isActive: self.$isActive) { Text("") }
Button(action: { self.isActive = true }) { LoginBtn() }

struct LoginBtn: View {
    var body: some View {
        Text("Login")
            .fontWeight(.bold)
            .padding()
            .foregroundColor(Color.white)
            .background(Color.orange)
            .cornerRadius(5.0)
    }
}

Photo of current button

我想让按钮扩展到与所用 TextFields 的宽度相似。同样,我知道已经发布了答案,但出于某种原因我无法让我的工作。谢谢!

声明您自己的按钮样式:

struct WideOrangeButton: ButtonStyle {

    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .padding()
            .frame(minWidth: 0,
                   maxWidth: .infinity)
            .foregroundColor(.white)
            .padding()
            .background( RoundedRectangle(cornerRadius: 5.0).fill(Color.orange)
        )
    }
}

然后像这样使用它:

Button(action: { self.isActive = true }) {
        Text("Login")
           .fontWeight(.bold)
    }   .buttonStyle(WideOrangeButton())

我喜欢这种方法,因为它让我可以使用默认按钮样式,但仍然会产生更宽的按钮。

Button(action: {
    // Whatever button action you want.
}, label: {
    Text("Okay")
        .frame(maxWidth: .infinity)
})
.buttonStyle(.automatic)