键盘打开时如何避免应用程序缩放?
How do I avoid app zoom when keyboard opens?
当我单击 SwiftUI 文本字段并打开键盘时,应用会缩小(如 video 所示)。
我对这种行为有两个问题:
- 为什么会这样?
- 如何避免这种情况发生?
这是我的代码:
struct BestillView: View { // This view is put inside a tab view with .ignoresSafeArea
@State var navn = ""
@State var varsling = true
var body: some View {
NavigationView {
ZStack {
Color("BackgroundColor")
.ignoresSafeArea()
VStack {
Image("Liquid") // This is my image overlayed on the background, i suspect this may be the only element that actually gets zoomed out
.resizable()
.aspectRatio(contentMode: .fit)
.ignoresSafeArea()
Spacer()
}
VStack {
ZStack(alignment: .leading) { // This is where the text field i'm having trouble with is
Color("UnselectedColor")
.frame(height: 50)
.cornerRadius(20.0)
if navn.isEmpty { // I have a separate text element as the placeholder text so i can give it a custom color
Text("Navn")
.foregroundColor(Color("AccentColor"))
.padding()
}
TextField("", text: $navn)
.padding()
}
.frame(width: 300)
Spacer()
.frame(height: 20.0)
// I removed the rest of my code, I don't think it should be necessary in this question - it's only a NavigationLink and a Toggle
}
}
}
}
}
您的图像上有 .ignoresSafeArea(),但实际上您在包含该图像的 VStack 上需要它。 VStack 正在缩小以适应键盘的安全区域,这也会挤压图像。
视野实际上并没有缩小;图像正在缩小 - 因为随着视图向上移动,适合的高度变小。
您可以将代码更新为:
Image("Liquid")
.aspectRatio(contentMode: .fill)
并且它将保持大小不变 - 因为宽度将保持不变。
当我单击 SwiftUI 文本字段并打开键盘时,应用会缩小(如 video 所示)。
我对这种行为有两个问题:
- 为什么会这样?
- 如何避免这种情况发生?
这是我的代码:
struct BestillView: View { // This view is put inside a tab view with .ignoresSafeArea
@State var navn = ""
@State var varsling = true
var body: some View {
NavigationView {
ZStack {
Color("BackgroundColor")
.ignoresSafeArea()
VStack {
Image("Liquid") // This is my image overlayed on the background, i suspect this may be the only element that actually gets zoomed out
.resizable()
.aspectRatio(contentMode: .fit)
.ignoresSafeArea()
Spacer()
}
VStack {
ZStack(alignment: .leading) { // This is where the text field i'm having trouble with is
Color("UnselectedColor")
.frame(height: 50)
.cornerRadius(20.0)
if navn.isEmpty { // I have a separate text element as the placeholder text so i can give it a custom color
Text("Navn")
.foregroundColor(Color("AccentColor"))
.padding()
}
TextField("", text: $navn)
.padding()
}
.frame(width: 300)
Spacer()
.frame(height: 20.0)
// I removed the rest of my code, I don't think it should be necessary in this question - it's only a NavigationLink and a Toggle
}
}
}
}
}
您的图像上有 .ignoresSafeArea(),但实际上您在包含该图像的 VStack 上需要它。 VStack 正在缩小以适应键盘的安全区域,这也会挤压图像。
视野实际上并没有缩小;图像正在缩小 - 因为随着视图向上移动,适合的高度变小。
您可以将代码更新为:
Image("Liquid")
.aspectRatio(contentMode: .fill)
并且它将保持大小不变 - 因为宽度将保持不变。