swiftswiftui

how to add plus button to list section in the sidebar


How do I show a plus button at the section header of the list view? The screenshot attached is the Mail app from MacOS. E.g. the code below adds button at the top, which I dont want, but would like it for each section.

Picture of mail app from mac os

import SwiftUI

struct ContentView: View {
    @State private var items: [String] = ["Inbox", "Sent"]
    @State private var selectedItem: String? = "Inbox"
    
    var body: some View {
        NavigationSplitView {
            List(selection: $selectedItem) {
                Section(header: Text("Favorites")) {
                    ForEach(items, id: \.self) { item in
                        Label(item, systemImage: item == "Inbox" ? "tray" : "paperplane")
                            .tag(item)
                    }
                }
            }
            .toolbar {
                ToolbarItem(placement: .automatic) {
                    Button(action: {
                        // Add action for the "+" button
                        addNewItem()
                    }) {
                        Image(systemName: "plus")
                    }
                }
            }
            .listStyle(SidebarListStyle()) // Sidebar appearance
        } detail: {
            if let selectedItem = selectedItem {
                Text("\(selectedItem) Details")
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
            } else {
                Text("Select an item")
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
            }
        }
    }
    
    private func addNewItem() {
        // Example action for adding a new item
        items.append("New Item \(items.count + 1)")
    }
}

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

enter image description here


Solution

  • you could try using a HStack, such as

    Section(header:
        HStack{
          Text("Favorites")
          Spacer()
          Button(action: { addNewItem() }) {
              Image(systemName: "plus.circle")
          }.buttonStyle(.plain)
        })
      ....