SwiftUI中自定义通用视图修饰符的一些用法不能编译



我正试图用一个自定义的修改器来替换一个标准的工作表修改器,该修改器对所有工作表的内容应用相同的更改,就像对主视图一样(它可以用于更改重音颜色,尽管有一个UIKit方法,但我特别想将privacySensitive修饰符应用于所有表)。

创建修饰符的代码编译ok:

import SwiftUI
struct SheetForItem<T, C>: ViewModifier where T: Identifiable, C: View {
var item: Binding<T?>
var onDismiss: (() -> Void)? = nil
var sheetContent: (T) -> C
func body(content: Content) -> some View {
content.sheet(item: item, onDismiss: onDismiss) {
sheetContent($0).privacySensitive()
}
}
}
extension View {
func appSheet<T, Content>(
item: Binding<T?>,
onDismiss: (() -> Void)? = nil,
content: @escaping (T) -> Content
) -> some View where T: Identifiable, Content: View {
modifier(SheetForItem(item: item, onDismiss: onDismiss, sheetContent: content))
}
}

大多数情况下它可以工作,但是appSheet在其他修饰符链中的一些用法而不是sheet不会编译错误:

Type()不能符合View.

下面的例子不能编译(但如果我用sheet替换appSheet,它将编译):

import SwiftUI
enum Actions:Identifiable {
case action1
case action2
var id: Self { self }
}
struct AppSheetExample: View {
@State var showActions = false
@State private var action: Actions?
var body: some View {
Button { showActions = true } label: {
Image(systemName: "square.and.pencil")
.resizable()
.scaledToFit()
.frame(width: 24, height: 24)
}
.confirmationDialog("Actions", isPresented: $showActions, titleVisibility: .visible) {
Button("Action 1") { action = .action2 }
Button("Action 2") { action = .action2 }
}
.appSheet(item: $action) { sheet in
switch sheet {
case .action1: Text("Action 1")
case .action2: Text("Action 2")
}
}
}
}

谢谢!

你需要用@ViewBuilder标记你的内容闭包,因为你没有显式返回View(即:return Text("Action 1")):

extension View {
func appSheet<Content>(
isPresented: Binding<Bool>,
onDismiss: (() -> Void)? = nil,
@ViewBuilder content: @escaping () -> Content
) -> some View where Content: View {
modifier(SheetIsPresented(isPresented: isPresented, onDismiss: onDismiss, sheetContent: content))
}

func appSheet<T, Content>(
item: Binding<T?>,
onDismiss: (() -> Void)? = nil,
@ViewBuilder content: @escaping (T) -> Content
) -> some View where T: Identifiable, Content: View {
modifier(SheetForItem(item: item, onDismiss: onDismiss, sheetContent: content))
}
}

相关内容

  • 没有找到相关文章

最新更新