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.
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()
}
}
}
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.
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()
}
}
}
Share
Improve this question
asked Nov 20, 2024 at 22:29
PranavPranav
5711 gold badge9 silver badges22 bronze badges
1 Answer
Reset to default 0you could try using a HStack
, such as
Section(header:
HStack{
Text("Favorites")
Spacer()
Button(action: { addNewItem() }) {
Image(systemName: "plus.circle")
}.buttonStyle(.plain)
})
....
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742324682a4422509.html
评论列表(0条)