如何在 SwiftUI 中使用函数返回 ToolbarItem?

Kar*_*rim 7 swift swiftui

我是 SwiftUI 的新手,我尝试将额外的代码放入函数中,但收到一些错误消息,但我不知道如何修复:

'some' types are only implemented for the declared type of properties and subscripts and the return type of functions

我的代码:

func test() -> ToolbarItem<Void, some View> {
   return ToolbarItem(direction: .right) {
        Label("", systemImage: "icloud.and.arrow.up.fill")
            .foregroundColor(.white)
            .frame(width: itemWith, height: 30, alignment: .center)
   }
}
Run Code Online (Sandbox Code Playgroud)

有谁知道如何做到这一点?谢谢

小智 13

@ToolbarContentBuilder
func toolbars() -> some ToolbarContent {
    ToolbarItem(placement: .navigationBarLeading) {
        Button {
                
        } label: {
            Image(systemName: "chevron.left")
        }
    }
    
    ToolbarItem(placement: .navigationBarTrailing) {
        Button {
            
        } label: {
            Image(systemName: "camera.fill")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

ToolbarContentBuilder从多表达式闭包构造工具栏项集。


Mah*_* BM 11

func test() -> some ToolbarContent {
    ToolbarItem(placement: ToolbarItemPlacement.navigationBarTrailing) {
        Label("", systemImage: "icloud.and.arrow.up.fill")
            .foregroundColor(.white)
            .frame(width: itemWith, height: 30, alignment: .center)
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是您要找的。请注意 ,Toolbar(placement:)而不是您写的Toolbar(direction:)。我认为direction这不是一个有效的参数。
作为解释,您需要使用协议ToolbarContent来返回全局函数中具有通用参数的工具栏内容。