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

SwiftUI中如何为TextField的高度变化添加动画效果?

为多行TextField的高度变化添加动画

你的代码已经实现了垂直方向TextField在不超过5行时自动增高的效果,但缺少高度变化的过渡动画。可以通过以下方式为高度变化添加平滑动画:

方案一:基于文本变化的显式动画

直接为TextField添加动画修饰符,监听文本内容的变化,让高度调整过程带有过渡效果:

struct TextClipView: View {
    @EnvironmentObject var textClipModel: TextClipModel
    private var placeholderString = "Type your text here!"
    
    var body: some View {
        GeometryReader { proxy in
            VStack(spacing: 20) {
                Spacer()
                    .frame(height: 80)
                
                TextField(placeholderString, text: $textClipModel.textClip, axis: .vertical)
                    .textFieldStyle(.roundedBorder)
                    .lineLimit(5)
                    // 添加动画:监听文本变化,应用缓入缓出过渡
                    .animation(.easeInOut(duration: 0.3), value: textClipModel.textClip)
                Spacer()
            }
            .frame(
                width: proxy.size.width,
                height: proxy.size.height
            )
        }
        .background(Color.green.opacity(0.2))
    }
}

说明

  • .animation(.easeInOut(duration: 0.3), value: textClipModel.textClip) 会在文本内容变化时,为TextField的高度调整应用0.3秒的缓入缓出动画。
  • 你可以自定义动画曲线和时长:比如用.spring()替换.easeInOut获得弹性动画效果,或者调整duration参数改变动画快慢。

方案二:容器级动画(兼容特殊场景)

如果直接给TextField加动画不生效(比如某些TextField样式的限制),可以将TextField包裹在容器中,给容器添加动画:

struct TextClipView: View {
    @EnvironmentObject var textClipModel: TextClipModel
    private var placeholderString = "Type your text here!"
    
    var body: some View {
        GeometryReader { proxy in
            VStack(spacing: 20) {
                Spacer()
                    .frame(height: 80)
                
                // 用VStack包裹TextField,给容器添加动画
                VStack {
                    TextField(placeholderString, text: $textClipModel.textClip, axis: .vertical)
                        .textFieldStyle(.roundedBorder)
                        .lineLimit(5)
                }
                .animation(.easeInOut(duration: 0.3), value: textClipModel.textClip)
                
                Spacer()
            }
            .frame(
                width: proxy.size.width,
                height: proxy.size.height
            )
        }
        .background(Color.green.opacity(0.2))
    }
}

注意事项

确保你的TextClipModel中的textClip属性使用@Published修饰,这样视图才能监听到文本变化并触发动画:

class TextClipModel: ObservableObject {
    @Published var textClip = ""
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 16:12:34