swiftui - How to make a view max. width with padding in SwiftUI
问题描述
I'm figuring out how to make views adaptable to different screen sizes in SwiftUI. Currently, I'm trying to create a register screen that should have a certain maximum width, but still have a padding if the maximum width can't be applied on small screen sizes.
I'm using a GeometryReader at the root to retrieve the width of the view and to apply it to the "Register" button. So I tried adding a padding to the GeometryReader, but without success. The reason is, that you can set the maxWidth on the GeometryReader doesn't work, it gets wider than the screen size.
My code looks like this:
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)
}
}
解决方案
If I got what you're trying to do, you can just use the padding
modifier on the GeometryReader
:
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)
}
}
EDIT: look the result with maxWidth = 10000
推荐阅读
- mongodb - 如何在 Golang 中跨包管理 MongoDB 客户端
- javascript - 如果日期出现在“2020 年 5 月 20 日 16:00:00”中,如何将日期格式化为 javascript 中的 mm/dd/yyyy?
- php - 为重力形式的 wordpress 重力视图插件添加额外的状态
- scala - Spark scala - 在df中查找非零行
- r - 每次在 linux 命令行中使用 Rscript 时都需要 install.packages 吗?
- python - 如何通过使用 pytest 测试 Flask 应用程序来设置和获取 cookie?
- vue.js - Vue 2 cli 控制台在发布版本中关闭?
- python - 如何在 python discord bot 中获取用户输入?
- java - 使用回调解决长期执行的递归
- c# - 布雷泽。如何在 Startup 类中获取当前 url(方法 ConfigureServices)?