我们创建了一个自定义视图扩展来扩展功能.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.showAlert
is@Published var showAlert: Bool
和AlertX
is 一个自定义视图,其中包含我们的专有自定义项以适应我们的 B2B 应用程序。
我遇到的问题 .alertX(isPresented:
是每次视图加载或更改状态时都会调用闭包中的信息,无论$viewModel.showAlert
绑定是否更改。.alert
仅在$viewModel.showAlert
值更改时才调用的内置视图扩展并非如此。
我需要在实现中进行哪些修改,public func alertX(isPresented: Binding<Bool>, content: () -> AlertX) -> some View {
以便仅在绑定值更改时才调用闭包内的信息?