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

如何让Image与TextEditor文本在TextEditor内垂直居中?

问题:让Image与TextEditor内文本垂直居中对齐

我希望Image与TextEditor中的文本能够在TextEditor内垂直居中(效果与下方的TextField一致)。我尝试使用GeometryReader以及各种对齐技巧,但都没有效果。

代码如下:

HStack {
    Image(systemName: "person.crop.rectangle")
        .foregroundColor(Color("ButtonTwo"))
   
    TextEditor(text: $userBio)
        .foregroundColor(.gray)
        .padding(.leading, 20)
}

当前效果截图:
未对齐的布局效果


解决方案

TextEditor基于UIScrollView实现,默认会把文本顶在容器顶部,直接设置HStack对齐无法生效。可以用以下两种方式实现和TextField一致的垂直居中效果:

方法一:用ZStack模拟占位文本对齐

通过隐藏的占位文本匹配TextEditor的默认内边距,让Image和占位文本(也就是编辑时的起始位置)垂直居中:

HStack(alignment: .center, spacing: 16) {
    Image(systemName: "person.crop.rectangle")
        .foregroundColor(Color("ButtonTwo"))
    
    ZStack(alignment: .topLeading) {
        // 空内容时显示占位文本,用于对齐基准
        if userBio.isEmpty {
            Text("输入你的简介...")
                .foregroundColor(.gray)
                .padding(.leading, 4)
                .padding(.top, 8) // 匹配TextEditor默认顶部内边距
        }
        TextEditor(text: $userBio)
            .foregroundColor(.gray)
            .padding(4)
    }
}

方法二:固定高度+对齐指南(iOS 16+)

给TextEditor设置和TextField一致的最小高度,通过对齐指南调整内容位置:

HStack(alignment: .center, spacing: 16) {
    Image(systemName: "person.crop.rectangle")
        .foregroundColor(Color("ButtonTwo"))
    
    TextEditor(text: $userBio)
        .foregroundColor(.gray)
        .padding(.leading, 20)
        .scrollContentBackground(.hidden)
        .frame(minHeight: 44) // 匹配TextField常规高度
        .alignmentGuide(.center) { dimension in
            dimension[.bottom] - dimension.height / 2
        }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:52:06