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

标签 ios swift xcode swiftui ios13

我有这个

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

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

enter image description here enter image description here

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

最佳答案

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

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

我写了一个 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)
  }
}

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

关于ios - 使用 SwiftUI,TextField 始终位于键盘顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57497477/

相关文章:

objective-c - 如何在 Xcode 中为实例变量和方法创建文档?

swift - UIlabel 动画不适合屏幕

ios - 状态栏在 iPhone 4S 上不显示

ios - 无法验证适用于 iOS App Store 的应用程序,缺少 armv6 架构

ios - 获取 NSString 高度

arrays - 简单的快速数组追加不起作用

ios - 如果他们仍然拒绝,请偶尔请求 iOS 权限

ios - 单击时更新标签

ios - 当父类(super class)也是Codable时,如何在子类中使用CodingKeys?

xcode - 无法在单独的项目中引用类型