首页 > 解决方案 > 如何使用 SwiftUI 让按钮和标签共享相同的宽度?

问题描述

struct PasswordGenerator : View {
    var body: some View {
        NavigationView {
            VStack {
                Spacer()
                //123
                Text("Upon clicking the button the password\nwill also be copied so you\ncan simply paste")
                    .lineLimit(nil)
                Spacer()
                    //123
                    Button(action: generatePassword) {
                        HStack {
                            Image("GeneratorGlyph")
                            Text("Generate!").font(.title)
                            }
                            .accentColor(.white)
                                                .frame(minHeight: 56, maxHeight: 112)
                                                .frame(minWidth: 0, maxWidth: .infinity)
                        }
                        .background(LinearGradient(gradient: Gradient(colors: [Color.init(red: 48/255, green: 153/255, blue: 216/255), Color.init(red: 65/255, green: 165/255, blue: 237/255)]), startPoint: .topLeading, endPoint: .bottomTrailing), cornerRadius: 9)
                Spacer()
                }
                .navigationBarTitle(Text("Generator"), displayMode: .inline)
        }
    }
}

所以我有一个按钮和一个文本标签(我在它们两个上都写了一个 123 的注释,这样你更容易看到),我想知道如何让按钮与文本标签具有相同的宽度。

标签: swiftswiftui

解决方案


只需将填充添加到您的按钮:

.padding(.horizontal, 40)

推荐阅读