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

8

我无法弄清楚如何在SwiftUI中更改按钮的宽度。

我已尝试过以下方法: - 使用 .frame(minWidth: 0, maxWidth: .infinity)。 - 在按钮和导航链接周围使用 Spacer()。 - 在 Text 字段上使用 frame,并在按钮上使用 padding。 - 查看文档,以及在网上搜索到的其他一些内容。但是没有任何方法可以改变按钮的宽度。

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)
    }
}

当前按钮的照片

我希望按钮可以扩展到与使用的文本字段宽度类似。再次说明,我知道已经有答案发布了,但由于某种原因我无法使我的工作生效。谢谢!

2个回答

10

自定义按钮样式:

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())

9

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接