如何在弹出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") } } } }
代码说明:
keepSwipeExpanded状态变量:用来标记是否需要保持swipe按钮的展开状态。transaction修饰符:拦截SwiftUI的动画事务,当keepSwipeExpanded为true时,禁用所有动画,这样点击按钮后行不会自动滑回。onChange监听Alert状态:当Alert关闭(showingAlert变为false)时,重置keepSwipeExpanded为false,恢复动画效果,行会自动滑回原位。- Alert按钮回调:在用户点击「Archive」或「Cancel」时,关闭Alert,触发上述的状态重置,完成滑回动画。
内容的提问来源于stack exchange,提问作者Whirlwind
相关产品推荐
相关产品推荐

