在swiftui中显示插播广告时主视图正在重新加载

vbopmzt1  于 2023-01-12  发布在  Swift
关注(0)|答案(1)|浏览(218)

我想设计一个快速视图MainView(),其中一个插入式广告将被呈现,而无需重新加载MainView()。
我的策略是:
1.从GADInterstitialAd加载广告,
1.在UIViewController()上呈现广告,然后使UIViewControllerRepresentable在swiftui中可呈现。
1.使用fullScreenCover(isPresented:,内容:)修饰符。
但每次广告展示时,MainView()都会进入.onDisappear状态,广告关闭后,它会进入.onAppear状态。因此,MainView()会完全重新加载。我希望停止此重新加载问题。实际上,我应该如何在视图中展示广告?

b91juud3

b91juud31#

与其使用fullScreenCover进行演示,不如在ZStack中显示ViewController,例如:

struct ContentView: View {
    
    @State private var showAd = false
    
    var body: some View {
        ZStack {
            VStack {
                Text("Main View")
            }
            .task {
                //  Show AdView after a delay
                try? await Task.sleep(nanoseconds: 2_000_000_000)
                showAd = true
            }
            .onAppear {
                print("Appearing") // This is only called once
            }
            
            if showAd {
                AdView {
                    showAd = false
                }
                .edgesIgnoringSafeArea(.all)
            }
        }
    }
}

// Just an example view for testing
struct AdView: UIViewControllerRepresentable {
    
    let dismiss: () -> Void
    
    func makeUIViewController(context: Context) -> UIViewController {
        let vc = UIViewController()
        vc.view.backgroundColor = .red
        let button = UIButton(type: .custom, primaryAction: UIAction(handler: { _ in
            dismiss()
        }))
        button.setTitle("Dismiss", for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        vc.view.addSubview(button)
        vc.view.centerXAnchor.constraint(equalTo: button.centerXAnchor).isActive = true
        vc.view.centerYAnchor.constraint(equalTo: button.centerYAnchor).isActive = true
        return vc
    }
    
    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
    }
}

如果需要的话,在中动画化AdView应该是非常简单的。

相关问题