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

SwiftUI ExpandingTextFieldView非空值时不渲染问题求助

问题分析与解决

问题根源

  1. 占位符实现错误:直接修改绑定的text变量来显示占位符,会污染数据源;当父视图传递非空文本时,onAppear中的无意义赋值(text = text)会触发视图重复渲染,干扰布局计算。
  2. 布局约束缺失:fixedSize(vertical: true)强制视图仅占用内容最小空间,当TextEditor初始有文本但无高度基准时,SwiftUI的布局计算可能导致视图高度为0,看起来完全不渲染。

修复后的代码

import SwiftUI

public struct ExpandingTextFieldView: View {
    @Binding var text: String
    let placeholder: String
    @FocusState private var isFocused: Bool

    public init(
        text: Binding<String>,
        placeholder: String = "Enter your text here..."
    ) {
        self._text = text
        self.placeholder = placeholder
    }

    public var body: some View {
        ZStack(alignment: .topLeading) {
            // 仅在文本为空且未聚焦时显示占位符,不修改绑定数据源
            if text.isEmpty && !isFocused {
                Text(placeholder)
                    .foregroundColor(.gray)
                    .padding(EdgeInsets(top: 8, leading: 4, bottom: 8, trailing: 4))
            }
            TextEditor(text: $text)
                .focused($isFocused)
                .padding(4)
                .foregroundColor(.primary)
                // 设置最小高度,避免视图因布局计算问题消失
                .frame(minHeight: 44)
        }
    }
}

#Preview {
    @State @Previewable var textValue = "Initial non-empty text"
    ExpandingTextFieldView(
        text: $textValue,
        placeholder: "Type here..."
    )
    .overlay(RoundedRectangle(cornerRadius: 8).stroke(.gray.opacity(0.5), lineWidth: 2))
    .padding()
}

关键修改点

  • 占位符实现优化:用ZStack嵌套占位符文本,仅在文本为空且未聚焦时显示,彻底避免修改绑定的text变量,防止数据源污染。
  • 布局约束调整:移除fixedSize(vertical: true),改用frame(minHeight: 44)保证视图有最小高度,解决初始渲染时高度为0的问题。
  • 对齐优化:给TextEditor和占位符添加一致的内边距,保证视觉对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 22:33:26