0

我在视图中有一个按钮,用于列表中的条目。目前,无论您在行内的哪个位置点击,都会执行按钮的操作。

以下示例代码说明了这一点:

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

在这里,ItemListCell结构很重要。它包含两个按钮。如果我现在点击行中的某个位置,则会执行两个按钮的代码。这是应该的方式吗?我想实现点击按钮执行相应的代码,当点击其他地方的行时,应该执行第三个动作。

4

0 回答 0