SwiftUI中使用fullScreenCover时如何禁用弹出动画?
实现方法
你可以通过两种常用方案实现禁用fullScreenCover的默认弹出动画:
方案1:触发状态切换时禁用动画
在修改showModal状态的逻辑外层包裹withAnimation(.none),直接关闭本次状态变更对应的系统动画:
把你代码中Button的action部分替换为以下内容:
Button(action: { withAnimation(.none) { showModal.toggle() } }) { Text("Show Modal") .padding() .foregroundColor(.blue) }
如果需要同时关闭模态页 dismiss 时的动画,在dismiss逻辑处也用同样的withAnimation(.none)包裹状态修改代码即可。
方案2:全局禁用该fullScreenCover的所有动画
直接给fullScreenCover modifier添加transaction配置,不管通过什么方式触发模态的显隐,都会自动禁用动画,不需要修改所有状态变更的逻辑:
在你现有.fullScreenCover代码后追加.transaction modifier,完整代码示例如下:
struct TheFullCover: View { @State var showModal = false var body: some View { Button(action: { showModal.toggle() }) { Text("Show Modal") .padding() .foregroundColor(.blue) } .background(Color(.white)) .overlay( RoundedRectangle(cornerRadius: 10) .stroke(.red, lineWidth:1) ) .fullScreenCover(isPresented: $showModal, onDismiss: { }, content: { VStack { Text("Here I am") TheFullCover() } }) // 新增以下代码即可禁用所有该模态页的显隐动画 .transaction { transaction in transaction.disablesAnimations = true } } }
两种方案都可以实现模态页无动画立即显示/消失的效果,方案2适用场景更广泛,不需要额外修改所有状态变更的触发逻辑。
内容的提问来源于stack exchange,提问作者zumzum
相关产品推荐
相关产品推荐

