如何使视图最大。 SwiftUI 中带填充的宽度

How to make a view max. width with padding in SwiftUI

我正在研究如何在 SwiftUI 中使视图适应不同的屏幕尺寸。目前,我正在尝试创建一个应具有一定最大宽度的注册屏幕,但如果最大宽度不能应用于小屏幕尺寸,则仍然有填充。

我在根目录下使用 GeometryReader 来检索视图的宽度并将其应用于 "Register" 按钮。所以我尝试向 GeometryReader 添加填充,但没有成功。原因是,您可以在 GeometryReader 上设置 maxWidth 不起作用,它变得比屏幕尺寸更宽。

我的代码如下所示:

struct RegisterPage: View {
    @State private var email: String = ""
    @State private var username: String = ""
    @State private var password: String = ""

    var body: some View {
        GeometryReader { geometry in
            VStack {
                TextField("login.email_placeholder", text: self.$email)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .padding(.bottom)
                TextField("login.username_placeholder", text: self.$username)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .padding(.bottom)
                TextField("login.password_placeholder", text: self.$password)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .padding(.bottom)
                Button(
                    action: {},
                    label: {
                        Text("login.register_button")
                            .frame(width: geometry.size.width)
                            .padding()
                            .background(Color.blue)
                            .foregroundColor(Color.white)
                            .cornerRadius(5)
                    }
                )
            }
        }
        .frame(maxWidth: 500)
    }
}

如果我明白你想要做什么,你可以在 GeometryReader 上使用 padding 修饰符:

struct RegisterPage: View {
    @State private var email: String = ""
    @State private var username: String = ""
    @State private var password: String = ""

    var body: some View {
        GeometryReader { geometry in
            VStack {
                TextField("login.email_placeholder", text: self.$email)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .padding(.bottom)
                TextField("login.username_placeholder", text: self.$username)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .padding(.bottom)
                TextField("login.password_placeholder", text: self.$password)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .padding(.bottom)
                Button(
                    action: {},
                    label: {
                        Text("login.register_button")
                            .frame(width: geometry.size.width)
                            .padding()
                            .background(Color.blue)
                            .foregroundColor(Color.white)
                            .cornerRadius(5)
                    }
                )
            }
        }
        .frame(maxWidth: 500)
        .padding(50)
    }
}

编辑:maxWidth = 10000

查看结果