SwiftUI 表在 macOS Big Sur 上没有动画解雇

问题描述

我希望表格解雇动画就像外观一样,但相反。我认为这也是标准行为。例如,当您创建一个文件时,您可以在 Xcode 中看到它。

但是正如你所看到的,它在没有动画的情况下消失了

Demo

这是我的代码

struct ContentView: View {

    @State var isAnotherViewPresented: Bool = false

    var body: some View {
        HStack {
            Button(action: {
                isAnotherViewPresented.toggle()
            },label: {
                Text("Button")
            }).sheet(isPresented: $isAnotherViewPresented,content: {
                AnotherView()
            })
        }
        .frame(width: 500,height: 300,alignment: .center)
    }
}

struct AnotherView: View {

    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        vstack {
            Button(action: {
                presentationMode.wrappedValue.dismiss()
            },label: {
                Text("Close")
            })
        }.padding()
    }
}

我在

  • Mac mini(M1,2020 年)
  • macOS Big Sur 11.1 (20C69)
  • Xcode 12.3 (12C33)

但我可以复制这个

  • Mac mini(2018 年)
  • macOS Big Sur 11.0.1 (20B29)
  • Xcode 12.2 (12B45b)

解决方法

免责声明:我遇到/有同样的问题,如果我尝试通过绑定解除工作表,它只是消失而不是有动画。下面的解决方案对我有用,但我不清楚它为什么起作用。

解决方案

显然,您“附加”模态的视图会影响它从呈现到不呈现的转换方式。例如,在您的代码中,工作表附加到按钮视图:

Button(action: {
  isAnotherViewPresented.toggle()
 },label: {
   Text("Button")
      // sheet is attached here
 }).sheet(isPresented: $isAnotherViewPresented,content: {
    AnotherView()
})

当您在第二个视图中调用 presentationMode.wrappedValue.dismiss() 时,模态会震动并消失而不是滑开。但是,如果您将工作表附加到外部 HStack 视图,则它可以正常工作并按预期滑开:

var body: some View {
    HStack {
        Button(action: {
            isAnotherViewPresented.toggle()
        },label: {
            Text("Button")
        })
    }
    .frame(width: 500,height: 300,alignment: .center)
    .sheet(isPresented: $isAnotherViewPresented,content: {
       AnotherView()
    })
    // sheet is now here
}

对我来说,只要工作表没有附加到按钮上,动画就可以工作。我不知道为什么会这样,但它对我有用,希望对你也有用。

,

我终于想出了怎么做,在我的 SwiftUI 应用程序中,如果我在关闭工作表时执行此操作:

isSheetVisible = false
NSApp.mainWindow?.endSheet(NSApp.keyWindow!)

示例:

struct SheetView: View {
    @Binding var isSheetVisible: Bool

    var body: some View {
        Button("Close") {
            isSheetVisible = false
            NSApp.mainWindow?.endSheet(NSApp.keyWindow!)
        }
    }
}

Working