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

SwiftUI TextEditor设置固定高度时出现幽灵空白问题求助

SwiftUI Form 中 TextEditor 底部幽灵空白问题修复建议

问题根源

你遇到的底部幽灵空白,主要是fixedSize(horizontal: false, vertical: true)和Form的自适应布局逻辑冲突导致的。Form会自动调整内部控件的布局,而fixedSize强制TextEditor在垂直方向保持内容所需尺寸,和你设置的maxHeight:400规则冲突,当输入内容接近高度上限时,就会出现多余的空白区域。

修复方案1:移除fixedSize(最直接有效)

你已经通过frame(minHeight:200, maxHeight:400)限制了TextEditor的高度范围,不需要fixedSize来强制尺寸。移除后,TextEditor会在设定的高度范围内自动滚动,不会出现幽灵空白:

TextEditor(text: $description)
  .frame(minHeight: 200, maxHeight: 400)
  .disabled(processState.isRunning)
  .onChange(of: description) { _, newValue in
    if newValue.count > characterLimit {
      description = String(newValue.prefix(characterLimit))
    }
  }

修复方案2:用ScrollView包裹(针对Form布局干扰严重的情况)

如果Form的布局逻辑仍然影响TextEditor,可以将其放在ScrollView中,明确控制滚动区域:

ScrollView {
  TextEditor(text: $description)
    .frame(minHeight: 200, maxHeight: 400)
    .disabled(processState.isRunning)
}
.onChange(of: description) { _, newValue in
  if newValue.count > characterLimit {
    description = String(newValue.prefix(characterLimit))
  }
}

额外排查技巧

  • 给TextEditor加上.background(Color.red),直观查看它实际占用的区域,确认空白是TextEditor本身还是父视图(Form/Section)导致的
  • 检查Form的Section是否设置了额外的padding或spacing,这些也可能引发布局异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 12:15:59