English 中文(简体)
如何看待 图一
原标题:How to toggle Image on click within Table?
问题回答

采用<代码>Observation框架来尝试这一做法。 在修改<条码>项目时,由于意见,意见将复发。

@Observable class Item: Identifiable {  // <--- here
....
}

The issue here is that SwiftUI s Table does not directly support interactive elements like buttons within cells. You should use List instead, which is designed to handle user interaction with its elements.

为此:

import SwiftUI

struct TestView: View {
    @State private var items = [
        Item(id: 1, text: "Eins", isClicked: false),
        Item(id: 2, text: "Zwei", isClicked: true),
        Item(id: 3, text: "Drei", isClicked: false)
    ]

    var body: some View {
        List(items) { item in
            HStack {
                Text(item.text)
                Button(action: {
                    item.isClicked.toggle()
                }) {
                    Image(systemName: item.isClicked ? "checkmark.circle.fill" : "circle")
                }
            }
        }
    }
}

struct TestView_Previews: PreviewProvider {
    static var previews: some View {
        TestView()
    }
}

class Item: Identifiable {
    var id: Int
    var text: String
    var isClicked: Bool

    init(id: Int, text: String, isClicked: Bool) {
        self.id = id
        self.text = text
        self.isClicked = isClicked
    }
}




相关问题
SwiftUI: How do I position a button x points above a sheet?

I am trying to recreate a Maps-style UI with a persistent bottom sheet and controls fixed above. Apple Maps UI with controls above ☝️ Example here, the "Look Around" binoculars button and ...

How to access own window within SwiftUI view?

The goal is to have easy access to hosting window at any level of SwiftUI view hierarchy. The purpose might be different - close the window, resign first responder, replace root view or ...

热门标签