I have a List and items containing a Toggle
view. I would like to handle selection and toggle state separately. the toggle should be disabled when list item is not selected.
The problem is:
- first tap - selects the list item. (
selected = true
) - tap on toggle - set
selection = false
On UIKit, Button/Switch/etc... catch the 'tap' and do not pass through to TableView selection state.
struct ListView: View {
@State var selected = Set<Int>()
let items = (1...10).map { ItemDataModel(id: $0) }
var body: some View {
List(items) { item in
ListItemView(dataModel: item)
.onTapGesture { if !(selected.remove(item.id) != .none) { selected.insert(item.id) }}
}
}
}
struct ListItemView: View {
@ObservedObject var dataModel: ItemDataModel
var body: some View {
HStack {
Text(dataModel.title)
Spacer()
Toggle(
isOn:Binding<Bool>(get: {dataModel.isOn}, set: {dataModel.isOn = $0}),
label: { Text("toggle") })
}
}
}
class ItemDataModel: Hashable, Identifiable, ObservableObject {
let id: Int
let title: String
@Published var isOn: Bool = false
init(id: Int) {
self.id = id
title = "item (id)"
}
func hash(into hasher: inout Hasher) {
hasher.combine(title)
}
static func == (lhs: ItemDataModel, rhs: ItemDataModel) -> Bool {
return lhs.id == rhs.id
}
}
[Please try to ignore syntax errors (if exsist) and focus on the gesture issue]