You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中如何忽略键盘工具栏的水平安全区域?

SwiftUI键盘ToolbarItem横屏无法全屏的问题

我使用ToolbarItem(placement: .keyboard)在键盘上方添加按钮,但iPhone横屏时按钮无法全屏显示,效果如图所示,十分不美观。

iPhone横屏时键盘上方按钮未全屏的截图

以下是示例代码片段:

struct ContentView: View {

  @State private var text: String = ""
  @FocusState private var isTextFieldFocused: Bool

  var body: some View {
    VStack {
      Text("A Text Field Below.")
      TextField("Enter text here.", text: $text)
        .frame(height: 44)
        .textFieldStyle(.roundedBorder)
        .focused($isTextFieldFocused)
    }
    .onAppear {
      self.isTextFieldFocused = true
    }
    .toolbar {
      ToolbarItem(placement: .keyboard) {
        _keyboardDismissButton()
      }
    }
  }

  @ViewBuilder
  private func _keyboardDismissButton() -> some View {
    Button {
      self.isTextFieldFocused = false
    } label: {
      Image(systemName: "keyboard.chevron.compact.down")
        .foregroundColor(.secondary)
        .frame(height: 44)
        .frame(maxWidth: .infinity)
        .contentShape(Rectangle())
    }
    .buttonStyle(.plain)
  }
}

我尝试使用.ignoresSafeArea(.all, edges: .horizontal)及相关组合,但均无效,按钮修饰符无作用。

我知道UIKit可实现该效果,想了解SwiftUI是否有解决办法,或这是否为已知问题?我认为这并非预期设计...

环境:

  • Xcode 15.0 (15A240d)
  • iOS 17.0

内容的提问来源于stack exchange,提问作者Kjuly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 11:17:16