使用 SwiftUI,TextField 始终位于键盘顶部

Kev*_*OUX 4 xcode ios swift ios13 swiftui

我有这个

struct ContentView: View {
    var body: some View {
        ZStack(alignment: Alignment.bottom) {
            List {
                Text("Default text").foregroundColor(Color.red)
            }
            TextField("Placeholder", text: .constant(""))
                .frame(minHeight: 30)
                .cornerRadius(8.0)
                .padding(10)
                .background(Color.blue)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

实际上,当我专注于 TextField 时,键盘会隐藏此文本字段。

在此处输入图片说明在此处输入图片说明

SwiftUI 中是否有一个简单的解决方案可以使文本字段始终位于键盘顶部?

Nic*_*Fox 5

这是观察NotificationCenter与键盘相关的通知的片段,并根据计算出的键盘高度更改间隔视图的高度。

import Combine
struct ExampleView: View {

  @State var keyboardHeight: CGFloat = 0
  var cancellables: Set<AnyCancellable> = []

  init() {
      NotificationCenter.default.publisher(for: UIResponder.keyboardWillChangeFrameNotification)
        .merge(with: NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification))
        .compactMap({ notification in
          guard let keyboardFrameValue: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return nil }
          let keyboardFrame = keyboardFrameValue.cgRectValue
          // If the rectangle is at the bottom of the screen, set the height to 0.
          if keyboardFrame.origin.y == UIScreen.main.bounds.height {
            return 0
          } else {
            // Adjust for safe area
            return keyboardFrame.height - (UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0)
          }
        })
        .assign(to: \.keyboardHeight, on: self)
        .store(in: &cancellables)
  }

  var body: some View {
    VStack {

      // Your content here

      Spacer()
        .frame(height: keyboardHeight)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我写了一个 Swift 包来为你处理这个问题。它公开了一个KeyboardObservingView包装你的内容。

它可以在这里找到:https : //github.com/nickffox/KeyboardObserving

你会像这样使用它:

var body: some View {
  KeyboardObservingView {
    List {...}
    TextField("Placeholder", text: .constant(""))
      .frame(minHeight: 30)
      .cornerRadius(8.0)
      .padding(10)
      .background(Color.blue)
  }
}
Run Code Online (Sandbox Code Playgroud)

这是正在使用的包的图像: demo