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

SwiftUI中使用contextMenu实现iMessage风格消息反应气泡的问题

实现类iMessage/Instagram/WhatsApp的消息交互效果

问题背景

我想要复刻iMessage、Instagram和WhatsApp里的消息长按交互效果——长按消息时弹出反应气泡+操作菜单。目前已经能单独实现消息视图和contextMenu,但两者配合时始终达不到流畅自然的体验。

问题1:预览视图抖动+多余白色背景

我尝试通过contextMenu的preview将反应气泡堆叠在消息上方,但消息气泡会出现明显抖动,且预览区域后方会出现不受欢迎的白色背景。

对应代码:

var body: some View {
    MessageView
        .contextMenu {
            Button(action: {
                // 执行复制操作
            }) {
                Text("Copy Message")
                Image(systemName: "doc")
            }
        } preview: {
            VStack {
                ReactionsView
                MessageView
            }
        }
}

var MessageView : some View {
    ZStack {
        RoundedRectangle(cornerRadius: 15)
            .frame(width: 150, height: 40)
            .foregroundColor(.accentColor)
        Text("Hello, World!")
    }
}

var ReactionsView : some View {
    ZStack {
        RoundedRectangle(cornerRadius: 20)
            .foregroundColor(Color(.systemGray5))
            .frame(width: 200, height: 50)
            .clipped()
        HStack(spacing: 20) {
            Image(systemName: "heart.fill")
                .foregroundColor(.red)
            Image(systemName: "hands.clap.fill")
                .foregroundColor(.green)
            Image(systemName: "hand.thumbsup.fill")
                .foregroundColor(.blue)
        }
    }
}

问题2:Overlay自动消失+抖动仍存在

之后我把preview改成用overlay实现,消息气泡抖动的问题依然存在,而且反应气泡的overlay会很快消失。

对应代码:

var body: some View {
    MessageView
        .contextMenu {
            Button(action: {
                // 执行复制操作
            }) {
                Text("Copy Message")
                Image(systemName: "doc")
            }
        } preview: {
            MessageView
                .overlay {
                    ReactionsView
                        .offset(y: -50)
                }
        }
}

我试了很多变体,结果都大同小异。请问该如何调整才能实现和主流通讯应用一致的流畅交互效果?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 19:45:28