显示键盘后SwiftUI底部安全区域未缩小

p1tboqfb  于 2023-02-21  发布在  Swift
关注(0)|答案(1)|浏览(158)

如果激活TextField后按下Open link按钮,NavigationLink将打开,之后如果返回上一屏幕,VStackTextField将停留在屏幕中间。因为底部SafeArea将通过键盘展开。如果ZStack中的第一个视图是ScrollView,则会发生这种情况。键盘被禁用后,它应该回到底部。我该如何解决这个问题?

struct ContentView: View {
  @State private var text = ""
  
  var body: some View {
    NavigationStack {
      ZStack(alignment: .bottom) {
        ScrollView {
          Color.green.opacity(0.2)
            .frame(height: 1000)
        }
        .ignoresSafeArea(.keyboard)
        
        VStack {
          TextField("", text: $text, prompt: Text("Input"))
            .textFieldStyle(.roundedBorder)
            .padding()
          NavigationLink("Open link") {
            Text("Details view")
          }
        }
        .background { Color.red }
        .background(ignoresSafeAreaEdges: .bottom)
      }
    }
  }
}

bxjv4tth

bxjv4tth1#

您可以尝试使用@FocusState属性 Package 。添加以下3个命令行:

//1 
@FocusState private var nameIsFocused: Bool

//2
.focused($nameIsFocused)

//3
.simultaneousGesture(TapGesture().onEnded({ _ in
   nameIsFocused = false
}))

您编写的代码如下所示:

struct ContentView: View {
  @State private var text = ""
  //1
  @FocusState private var nameIsFocused: Bool

  var body: some View {
    NavigationStack {
      ZStack(alignment: .bottom) {
        ScrollView {
          Color.green.opacity(0.2)
            .frame(height: 1000)
        }
        .ignoresSafeArea(.keyboard)
        
        VStack {
          TextField("", text: $text, prompt: Text("Input"))
            //2
            .focused($nameIsFocused)
            .textFieldStyle(.roundedBorder)
            .padding()
            
          NavigationLink("Open link") {
            Text("Details view")
          }
          //3
          .simultaneousGesture(TapGesture().onEnded({ _ in
              nameIsFocused = false
          }))
        }
        .background { Color.red }
        .background(ignoresSafeAreaEdges: .bottom)
      }
    }
  }
}

结果:

希望对你有用!

相关问题