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

SwiftUI中如何限制动态TextEditor的最大高度?

解决TextEditor动态高度限制最大高度的问题

原代码通过隐藏的Text同步高度实现了TextEditor的自适应,但没有设置高度上限,导致输入内容过多时视图会无限展开。只需两处修改即可实现最大高度限制:

修改后的完整代码

struct TextEditorView: View {
    
    @Binding var string: String
    @State var textEditorHeight: CGFloat = 20
    // 自定义最大高度,按需调整数值
    let maxTextEditorHeight: CGFloat = 200
    
    var body: some View {
        
        ZStack(alignment: .leading) {
            Text(string)
                .font(.system(.body))
                .foregroundColor(.clear)
                .padding(14)
                .background(GeometryReader {
                    Color.clear.preference(key: ViewHeightKey.self,
                                           value: $0.frame(in: .local).size.height)
                })
            
            TextEditor(text: $string)
                .font(.system(.body))
                // 同时锁定最小高度和最大高度
                .frame(height: max(40, min(textEditorHeight, maxTextEditorHeight)))
                .cornerRadius(10.0)
                .shadow(radius: 1.0)
                // 超过最大高度时允许内容滚动
                .scrollContentBackground(.hidden)
        }
        .onPreferenceChange(ViewHeightKey.self) {
            // 更新高度时直接限制在最大值以内
            textEditorHeight = min($0, maxTextEditorHeight)
        }
        
    }
}

struct ViewHeightKey: PreferenceKey {
    static var defaultValue: CGFloat { 0 }
    static func reduce(value: inout Value, nextValue: () -> Value) {
        value = value + nextValue()
    }
}

关键修改说明

  • 新增maxTextEditorHeight常量,直接设定你需要的最大高度值
  • 在高度更新的回调里,把计算出的文本高度和最大高度取最小值,保证textEditorHeight不会突破上限
  • TextEditor的frame高度同时处理了最小高度(40)和最大高度限制,既不会太矮也不会无限增高
  • 加上scrollContentBackground(.hidden)是为了让超过高度后滚动的内容样式更统一,可根据需求选择保留或移除

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 11:47:29