I'm stuck on this very basic task where I have a tableView and I want whenever the user clicks on the button it will remove the last element and update it on the tableview. I've tried the following but for some reason, this doesn't work. I assume it's something to do with the @state? it works when I select an element but whenever I click the button it ignores it
struct ContentView: View {
var tableView = CustomTableView()
var body: some View {
VStack{
tableView
Button("hello", action: tableView.removeElement)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct CustomTableView : UIViewRepresentable {
@State var items = ["hello", "world", "great", "day"]
let table = UITableView()
func removeElement() {
items.removeLast()
print(items.count)
table.reloadData()
}
func makeUIView(context: Context) -> UITableView {
table.delegate = context.coordinator
table.dataSource = context.coordinator
return table
}
func updateUIView(_ table: UITableView, context: Context) {
table.separatorStyle = .none
}
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
}
class Coordinator : NSObject, UITableViewDataSource, UITableViewDelegate {
var parent: CustomTableView
init(_ parent: CustomTableView) {
self.parent = parent
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedItem = parent.items[indexPath.row]
parent.items.removeAll { (item) -> Bool in
return item == selectedItem
}
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return parent.items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
cell.textLabel?.text = parent.items[indexPath.row]
return cell
}
}
}