Karim
Karim

Reputation: 402

How to use function return ToolbarItem in SwiftUI?

I am new to SwiftUI,I tried to put the extra code into the function, but I get some error message and I don't know how to fix:

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

My code:

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)
   }
}

Does anyone know how to do this? thank you

Upvotes: 13

Views: 2466

Answers (2)

chenxi
chenxi

Reputation: 221

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

ToolbarContentBuilder Constructs a toolbar item set from multi-expression closures.

Upvotes: 20

Mahdi BM
Mahdi BM

Reputation: 2104

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

this is what you're looking for. Notice the Toolbar(placement:) instead of the one you wrote Toolbar(direction:). I don't think direction is a valid parameter.
As an explanation, You need to use to the protocol ToolbarContent to return toolbar stuff that have generic arguments, within a global func.

Upvotes: 13

Related Questions