SwiftUI 删除全屏覆盖的过渡

Mun*_*der 5 swift swiftui

有什么方法可以删除全屏封面的动画/过渡吗?这是我的代码:

let contentView = UIHostingController(rootView: ContentView())
    override func viewDidLoad() {
        super.viewDidLoad()
        configureBackgroundGradient()
        addChild(contentView)
        view.addSubview(contentView.view)
        setupContraints()
 }


struct ContentView: View {
    var body: some View {
        EmptyView().fullScreenCover(isPresented: .constant(true), content: {
            FullScreenView.init()
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助!

小智 8

您可以使用withTransaction禁用视图之间的过渡动​​画

var transaction = Transaction()
transaction.disablesAnimations = true
withTransaction(transaction) {
   self.isPresentedViewB = true
}
Run Code Online (Sandbox Code Playgroud)

https://developer.apple.com/documentation/swiftui/transaction


Raj*_*han 2

用于open class func setAnimationsEnabled(_ enabled: Bool)禁用整个应用程序的动画。

就您而言,您只需在全屏演示期间禁用动画并在演示后重新开始。

这是可能的解决方案

override func viewDidLoad() {
    super.viewDidLoad()
    configureBackgroundGradient()
    UIView.setAnimationsEnabled(false) //<== Disable animation for whole app
    addChild(contentView)
    view.addSubview(contentView.view)
    DispatchQueue.main.async {
        UIView.setAnimationsEnabled(true) //<== Again enable animation for whole app
    }
    setupContraints()
}
Run Code Online (Sandbox Code Playgroud)

你也可以把它写在里面ContentView而不是viewDidLoad

struct ContentView: View {
    @State private var isPresent: Bool = false{
        willSet {
            UIView.setAnimationsEnabled(false) //<== Disable animation for whole app
        } didSet {
            DispatchQueue.main.async {
                UIView.setAnimationsEnabled(true) //<== Again enable animation for whole app
            }
        }
    }
    var body: some View {
        EmptyView().fullScreenCover(isPresented: $isPresent, content: {
            FullScreenView.init()
        })
        .onAppear() {
            isPresent = true
        }
    }
}

Run Code Online (Sandbox Code Playgroud)

您也可以使用此扩展。

extension View {
    func withoutAnimation(_ work: @escaping () -> Void) {
        UIView.setAnimationsEnabled(false) //<== Disable animation for whole app
        work()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            UIView.setAnimationsEnabled(true) //<== Again enable animation for whole app
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

struct ContentView: View {
    @State private var isPresent: Bool = false
    
    var body: some View {
        EmptyView().fullScreenCover(isPresented: $isPresent, content: {
            FullScreenView.init()
        })
        .onAppear() {
            withoutAnimation {
                isPresent = true
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)