我正在尝试抽象一个警报,该警报在我的应用程序的多个地方使用。
我复制并粘贴了 的实现func alert(isPresented: Binding<Bool>, content: () -> Alert) -> some View
并对其进行了调整以使其适应我的使用情况:
extension View {
func externalURLAlert(isPresented: Binding<Bool>, action: ()) -> some View {
isPresented.wrappedValue ? AnyView(Alert(
title: Text("alert.externalURL.title".localized),
message: Text("alert.externalURL.message".localized),
primaryButton: .cancel(),
secondaryButton: .default(Text("alert.externalURL.openAction.title".localized)) {
action
}
)) : AnyView(EmptyView())
}
}
我的计划是在 View 上调用它,.externalURLAlert(isPresented: $isPresented, action: someAction)
但我无法编译该函数。
我得到的错误是以下一个:
初始化程序 'init(_:)' 要求 'Alert' 符合 'View'
修饰符的工作方式是返回调用它们的视图的修改版本。如果您调用Text("").foregroundColor(...)
,您将收到一个Text
具有新前景色的新视图。警报也是如此,如果您调用Text("").alert(...
,您会收到一个Text
可以在顶部显示警报的视图。
另一方面,您的修改器会完全删除该层次结构并将其替换为空视图或警报,但此警报没有关于它应该出现在何处的信息。
如果您想要显示标准化警报,您应该利用现有的修饰符和您自己的参数,如下所示:
extension View {
func externalURLAlert(isPresented: Binding<Bool>, action: ()) -> some View {
self.alert(isPresented: isPresented) {
Alert(
title: Text("alert.externalURL.title".localized),
message: Text("alert.externalURL.message".localized),
primaryButton: .cancel(),
secondaryButton: .default(Text("alert.externalURL.openAction.title".localized)) {
action()
}
)
}
}
}
注意 的使用self
,因为我们想要维护层次结构,并且.alert(...)
因为我们正在使用已经知道如何显示警报的现有系统修饰符。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句