首页 > 解决方案 > 影响模态背景的 SwiftUI 动画

问题描述

我在 ListView() 中有一张带有简单动画的表格:

        .overlay(
                ZStack{
                Group {
                    Circle()
                        .fill(Color.blue)
                        .opacity(animatingButton ? 0.2 : 0)
                        .frame(width: 68, height: 68, alignment: .center)
                        .scaleEffect(animatingButton ? 1 : 0)
                    
                    Circle()
                        .fill(Color.blue)
                        .opacity(animatingButton ? 0.15 : 0)
                        .frame(width: 88, height: 88, alignment: .center)
                        .scaleEffect(animatingButton ? 1 : 0)
                }
                .animation(Animation.easeInOut(duration: 2.0).repeatForever(autoreverses: true))

导致圆圈的大小不断扩大和缩小。

在模态中,我有一个 TabView 并设置了一个背景图像,如下所示:

TabView(selection: $VM.modalSelectedPage){
ListView()
    .background(Image(VM.backgroundImage)
        .resizable()
        .aspectRatio(contentMode: .fill)
        .edgesIgnoringSafeArea(.all)) 

....

}

问题是,如果我注释掉,从模态底部向上拖动时,此动画会导致不需要的行为

  .animation(Animation.easeInOut(duration: 2.0).repeatForever(autoreverses: true))

问题消失了。

我试过添加

.animation(nil) 

到 .background 不起作用。

在这里您可以看到问题:https ://imgur.com/E8S01kd

在这里你可以看到它在没有动画的情况下工作:https ://imgur.com/fjI0Aiz

复制错误的简单代码

模态视图:

import SwiftUI

struct ModalView: View {

var body: some View {
    
        
        HStack{
            Text("")
                .animation(.default) // Comment out to fix issue
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.green)                                                             
        .edgesIgnoringSafeArea(.all)
    }
}

内容视图:

import SwiftUI

    struct ContentView: View {
    
        @State private var showingModal = false
    
        var body: some View {
            Button(action: {
            self.showingModal.toggle()   
        }, label: {
            Text("Open Modal")
        })
        .sheet(isPresented: $showingModal, content: {
            ModalView()
        }) 
    }
}

标签: swiftswiftui

解决方案


推荐阅读