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

如何在弹出Alert时阻止列表行的滑回动画?

解决方案:阻止Swipe行自动滑回,直到Alert交互完成

这是可行的,我们可以通过禁用swipe关闭动画的方式,让行保持展开状态,直到用户处理完Alert后再恢复动画,触发滑回效果。

修改后的代码:

struct ContentView: View {
    @State private var showingAlert = false
    @State private var keepSwipeExpanded = false
    
    var body: some View {
        List {
            Text("Archive")
                .swipeActions(edge: .trailing, allowsFullSwipe: false) {
                    Button {
                        // 标记需要保持swipe展开状态
                        keepSwipeExpanded = true
                        showingAlert = true
                    } label: {
                        Image(systemName: "archivebox.fill")
                    }
                    .tint(.yellow)
                }
                // 拦截动画:当需要保持展开时,禁用所有动画
                .transaction { transaction in
                    if keepSwipeExpanded {
                        transaction.animation = nil
                    }
                }
                // Alert关闭时,取消展开标记,恢复动画
                .onChange(of: showingAlert) { _, isPresented in
                    if !isPresented {
                        keepSwipeExpanded = false
                    }
                }
                .alert("Archive?", isPresented: $showingAlert) {
                    Button("Archive") {
                        // 这里添加你的归档业务逻辑
                        showingAlert = false
                    }
                    Button("Cancel", role: .cancel) {
                        showingAlert = false
                    }
                } message: {
                    Text("Some message")
                }
        }
    }
}

代码说明:

  1. keepSwipeExpanded状态变量:用来标记是否需要保持swipe按钮的展开状态。
  2. transaction修饰符:拦截SwiftUI的动画事务,当keepSwipeExpanded为true时,禁用所有动画,这样点击按钮后行不会自动滑回。
  3. onChange监听Alert状态:当Alert关闭(showingAlert变为false)时,重置keepSwipeExpanded为false,恢复动画效果,行会自动滑回原位。
  4. Alert按钮回调:在用户点击「Archive」或「Cancel」时,关闭Alert,触发上述的状态重置,完成滑回动画。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:35:09