【问题标题】:How do I avoid app zoom when keyboard opens?键盘打开时如何避免应用缩放?
【发布时间】:2021-06-22 00:19:53
【问题描述】:

当我单击我的 SwiftUI 文本字段并打开键盘时,应用程序会缩小(显示在 video 中)。

我对此行为有两个疑问:

  1. 为什么会这样?
  2. 如何避免这种情况发生?

这是我的代码:

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

【问题讨论】:

    标签: swift xcode swiftui keyboard textfield


    【解决方案1】:

    您的 Image 上有 .ignoresSafeArea(),但实际上在包含该 Image 的 VStack 上需要它。 VStack 正在缩小以适应键盘的安全区域,这也会挤压图像。

    【讨论】:

    • 很好的建议,但不幸的是这不起作用。
    • 我的小疏忽,这确实有效,但我需要在 所有 父视图上使用.ignoresSafeArea(),而不仅仅是 VStack。
    【解决方案2】:

    视图实际上并没有缩小;图像正在缩小 - 因为随着视图向上移动,它的高度越来越小。

    您可以将代码更新为:

    Image("Liquid")
        .aspectRatio(contentMode: .fill)
    

    它会保持大小不变​​ - 因为宽度将保持不变。

    【讨论】:

    • 这弄乱了图像的显示方式。 contentMode: .fit 看起来应该是这样,但 contentMode: .fill 不是。
    • 我明白了。我认为最好自己先看一下图像。但是,您也可以在图像上尝试.ignoresSafeArea(.keyboard, edges: .bottom) 吗? @马丁
    • 我已修复,请参阅标记为已解决的答案 :)
    猜你喜欢
    • 2020-11-04
    • 2017-11-25
    • 2023-03-23
    • 2022-10-25
    • 2019-05-06
    • 1970-01-01
    • 2020-07-25
    • 2012-10-08
    • 1970-01-01
    相关资源
    最近更新 更多