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

如何在Swift及SwiftUI中调整Text View文本视图的大小

SwiftUI TextEditor尺寸调整方案

你当前使用的TextEditor默认会填充父视图提供的全部可用空间,可通过以下几种方式调整尺寸:

  • 固定宽高设置
    直接给TextEditor添加frame修饰符指定固定的宽高数值,修改后的代码示例如下:
import SwiftUI
struct ContentView: View {
    @Binding var document: NavKov20193123Document
    var body: some View {
        TextEditor(text: $document.text)
            .frame(width: 350, height: 400) // 可自行修改为需要的宽高数值
            .foregroundColor(.gray)
            .lineSpacing(3)
            .allowsTightening(false)
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(document: .constant(NavKov20193123Document()))
    }
}
  • 自适应屏幕尺寸设置
    如果不需要固定死尺寸,希望适配不同设备屏幕大小,可以设置最大/最小宽高限制:
TextEditor(text: $document.text)
    .frame(minWidth: 200, maxWidth: .infinity, minHeight: 200, maxHeight: 600)
    .padding(.horizontal, 16) // 左右预留16边距,避免贴满屏幕边缘
    .foregroundColor(.gray)
    .lineSpacing(3)
    .allowsTightening(false)
  • 内容自适应高度设置
    如果需要让TextEditor的高度跟随输入的文本内容自动调整,可以结合@State变量监听内容高度动态修改:
import SwiftUI
struct ContentView: View {
    @Binding var document: NavKov20193123Document
    @State private var textEditorHeight: CGFloat = 100 // 初始默认高度
    var body: some View {
        TextEditor(text: $document.text)
            .frame(height: textEditorHeight)
            .foregroundColor(.gray)
            .lineSpacing(3)
            .allowsTightening(false)
            .background(
                GeometryReader { proxy in
                    Color.clear
                        .onChange(of: document.text) { _ in
                            // 计算文本实际高度赋值
                            let fitSize = proxy.sizeThatFits(.init(width: proxy.size.width, height: .greatestFiniteMagnitude))
                            textEditorHeight = min(fitSize.height, 600) // 最大高度限制为600,避免内容过长超出屏幕
                        }
                }
            )
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:24:02