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

如何在SwiftUI中实现ChatGPT打字机样式动画效果?

在SwiftUI中实现ChatGPT响应的打字机动画效果

要实现API返回响应时的打字机样式动画,你需要将完整文本拆分成逐字符展示的逻辑,下面是具体的修改方案:

1. 定义消息结构体

首先替换原来的字符串数组,改用可识别的消息结构体,区分用户消息和AI消息:

struct ChatMessage: Identifiable {
    let id = UUID()
    let content: String
    let isUserMessage: Bool
}

然后在ContentView中更新状态变量:

@State var messages = [ChatMessage]()

2. 创建打字机文本视图

专门实现一个TypewriterText视图,负责逐字符展示文本:

struct TypewriterText: View {
    let fullText: String
    @State private var displayedText = ""
    @State private var timer: Timer?
    
    var body: some View {
        Text(displayedText)
            .onAppear {
                startTyping()
            }
            .onDisappear {
                timer?.invalidate()
            }
    }
    
    private func startTyping() {
        displayedText = ""
        timer?.invalidate()
        var characterIndex = fullText.startIndex
        
        // 调整时间间隔可以改变打字速度,0.05为较快速度,0.1为较慢
        timer = Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { timer in
            guard characterIndex < fullText.endIndex else {
                timer.invalidate()
                return
            }
            displayedText.append(fullText[characterIndex])
            characterIndex = fullText.index(after: characterIndex)
        }
    }
}

3. 更新ContentView的UI和发送逻辑

修改消息列表的渲染逻辑,对AI消息使用打字机视图,用户消息保持普通文本:

var body: some View {
    VStack(alignment: .leading) {
        ForEach(messages) { message in
            if message.isUserMessage {
                Text(message.content)
                    .padding(.vertical, 4)
            } else {
                TypewriterText(fullText: message.content)
                    .padding(.vertical, 4)
            }
        }
        Spacer()
        HStack {
            TextField("type here ...", text: $text)
            Button("Send") {
                send()
            }
        }
    }
    .onAppear {
        viewModel.setup()
    }
    .padding()
}

同时更新send方法,添加消息时使用新的结构体:

private func send() {
    guard !text.trimmingCharacters(in: .whitespaces).isEmpty else { return }
    messages.append(ChatMessage(content: "Me: \(text)", isUserMessage: true))
    viewModel.send(text: text) { response in
        DispatchQueue.main.async {
            self.messages.append(ChatMessage(content: "ChatGPT: " + response, isUserMessage: false))
            self.text = ""
        }
    }
}

关键点说明

  • 利用Timer定时向显示文本中添加单个字符,模拟打字机效果
  • 在视图消失时销毁Timer,避免内存泄漏
  • 通过调整Timer的时间间隔,可以控制打字速度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 16:44:59