0

我们创建了一个自定义视图扩展来扩展功能.alert并添加一系列自定义以满足我们的需求;

import SwiftUI

extension View {
    
    public func alertX(isPresented: Binding<Bool>, content: () -> AlertX) -> some View {
        
        let alertX_view = AlertX_View(visible: isPresented, alertX: content())
        let alertXVC = AlertXViewController(alertX_view: alertX_view, isPresented: isPresented)
        alertXVC.modalPresentationStyle = .overCurrentContext
        alertXVC.view.backgroundColor = UIColor.clear
        alertXVC.modalTransitionStyle = .crossDissolve
        
        if isPresented.wrappedValue == true {
            if AlertX_View.currentAlertXVCReference == nil {
                AlertX_View.currentAlertXVCReference = alertXVC
            }
            
            let viewController = self.topViewController()
            viewController?.present(alertXVC, animated: true, completion: nil)
        } else {
            alertXVC.dismiss(animated: true, completion: nil)
        }
        
        return self
    }
    ... truncated for brevity
}

在视图上调用它的方式与调用 .alert 的方式相同;

        .alertX(isPresented: $viewModel.showAlert) {
            AlertX(logo: networkStore.currentNetwork.networkTheme.systemLogo ,
                   logoColor: networkStore.activeColors.lightTextColor ,
                   backgroundColor: networkStore.activeColors.primaryColor,
                   title: Text("AlertX Test"))
        }

Where $viewModel.showAlertis@Published var showAlert: BoolAlertXis 一个自定义视图,其中包含我们的专有自定义项以适应我们的 B2B 应用程序。

我遇到的问题 .alertX(isPresented: 是每次视图加载或更改状态时都会调用闭包中的信息,无论$viewModel.showAlert绑定是否更改。.alert仅在$viewModel.showAlert值更改时才调用的内置视图扩展并非如此。

我需要在实现中进行哪些修改,public func alertX(isPresented: Binding<Bool>, content: () -> AlertX) -> some View {以便仅在绑定值更改时才调用闭包内的信息?

4

1 回答 1

0

请记住,SwiftUI 会一直重新加载所有结构和函数——然后根据数据依赖关系决定重绘哪个部分。因此,您的视图函数中的任何代码都将运行。很多。

试试这个:在那个函数的顶部,把

guard isPresented.wrappedValue == true else {
    return
}

而不是稍后在函数中检查它。

相关,您可能还想考虑将此代码制作成 ViewModifier,然后您的 alertX 函数仅根据 isPresented 绑定应用 viewModifier,否则返回 self。

于 2021-06-05T16:50:51.100 回答