I have a button in a view that is used for entries in a list. Currently, the action of the button is executed no matter where you tap within the row.
The following sample code illustrates this:
import SwiftUI
// MARK: - Model
struct Item {
var id: Int
var name: String
var subItems: [Item]
var isFolder: Bool { subItems.count > 0 }
}
extension Item: Identifiable { }
class Model: ObservableObject {
var items: [Item]
internal init(items: [Item]) { self.items = items }
}
extension Model {
static let exmaple = Model(items: [
Item(id: 1, name: "Folder 1", subItems: [
Item(id: 11, name: "Item 1.1", subItems: []),
Item(id: 12, name: "Item 1.2", subItems: [])
]),
Item(id: 2, name: "Folder 2", subItems: [
Item(id: 21, name: "Item 2.1", subItems: []),
Item(id: 22, name: "Item 2.2", subItems: []),
Item(id: 23, name: "Item 2.3", subItems: [])
]),
Item(id: 3, name: "Item 1", subItems: []),
Item(id: 4, name: "Item 2", subItems: [])
])
}
// MARK: - View
struct MainView: View {
var body: some View {
NavigationView {
Form {
Section("Main…") {
NavigationLink {
ItemListView(items: Model.exmaple.items)
} label: {
Label("List", systemImage: "list.bullet.rectangle.portrait")
}
}
}
Label("Select a menu item", image: "menucard")
}
}
}
struct ItemListView: View {
var items: [Item]
var body: some View {
List(items) { item in
if item.isFolder {
NavigationLink {
ItemListView(items: item.subItems)
} label: {
ItemListCell(item: item)
}
} else {
ItemListCell(item: item)
}
}
.navigationBarTitle("List")
}
}
struct ItemListCell: View {
var item: Item
var body: some View {
HStack {
Image(systemName: item.isFolder ? "folder" : "doc")
Text(String(item.name))
Spacer()
if !item.isFolder {
Button {
print("button 1 item: \(item.name)")
} label: {
Image(systemName: "ellipsis.circle")
}
Button {
print("button 2 item: \(item.name)")
} label: {
Image(systemName: "info.circle")
}
}
}
}
}
// MARK: - App
@main
struct SwiftUI_TestApp: App {
var body: some Scene {
WindowGroup {
MainView()
}
}
}
Here, the ItemListCell
struct is important. It contains two buttons. If I now tap somewhere in the row, the code for both buttons is executed.
Is this the way it should be?
I would like to achieve that tapping the buttons executes the corresponding code and when tapping the row somewhere else, a third action should be executed.