Shark Deng
Shark Deng

Reputation: 1088

How to add space in toolbar items (SwiftUI)

the Spacer() has no effect in the ToolbarItem, I want to let items spread out rather than clustering. Do you know how to solve this? Thank you.

This is the code.

struct ContentView: View {
    
    var body: some View {
        NavigationView {
            VStack{
                Image("searchbar")
                Text("Test")
            }
            .toolbar {
                ToolbarItem(placement: .principal) {
                    HStack {
                        Text("9scoretrain")
                        Spacer()
                        NavigationLink(
                            destination: Text("SearchView"),
                            label: {
                                Image("searchbar")
                                    .resizable()
                                    .aspectRatio(contentMode: .fit)
                                    .frame(width:200)
                            })
                        Spacer()
                        NavigationLink(
                            destination: Text("CameraView"),
                            label: {
                                Image(systemName: "camera.viewfinder")
                            })
                    }
                }
            }
        }
    }
}

This is the current effect. enter image description here

This is the effect I want in which items are evenly distributed. enter image description here

Upvotes: 1

Views: 1985

Answers (1)

Shark Deng
Shark Deng

Reputation: 1088

This method might solve, but there is still some space between the centered item and the trailing item.

This is still not what I want, I want items are evenly distributed.

This is the effect. enter image description here

This is the code.

struct ContentView: View {
    
    var body: some View {
        NavigationView {
            VStack{
                Image("searchbar")
                Text("Test")
            }
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Text("9scoretrain")
                }
                
                ToolbarItem(placement: .principal) {
                    NavigationLink(
                        destination: Text("SearchView"),
                        label: {
                            Image("searchbar")
                                .resizable()
                                .aspectRatio(contentMode: .fit)
                                .frame(width:200)
                        })
                }
                
                ToolbarItem(placement: .navigationBarTrailing) {
                    NavigationLink(
                        destination: Text("CameraView"),
                        label: {
                            Image(systemName: "camera.viewfinder")
                        })
                }
            }
        }
    }
}

Upvotes: 1

Related Questions