问题
Each cell in my tableView has various properties:
class: Item
// properties
var name: String
var photo: UIImage?
var category: String
var instructions: String
var completed = false
(everything is initialized as well)
my tableView array is:
items = [Item]()
When Item.complete is true, the cell will have a checkmark accessory, else it'll have .none
I want to use a UIButton (in a separate VC) to make Item.complete = false for every cell in the tableView, thus removing all of the checkmarks and essentially resetting the data.
My items: Item array is variable, in that the user has the option to add or delete any row in the array.
I want the UIButton (located on a separate VC in a separate tab) to segue to the tableView and make the changes.
How can I change each cells .complete property to equal false with a UIButton so that I can remove the checkmark on every cell?
回答1:
You can also use the .map
function.
You cam run this directly in a Playground page:
class Item: NSObject {
var name: String = ""
var completed: Bool = false
}
// declare items array
var items = [Item]()
// fill with 20 Items,
// setting .completed for every-other one to true
for n in 0...19 {
let newItem = Item()
newItem.name = "item-\(n)"
newItem.completed = n % 2 == 0
items.append(newItem)
}
// print out the items in the array
print("Original values")
for item in items {
print(item.name, item.completed)
}
print()
// -- this is the .map function
// set .completed to false for every item in the array
items = items.map {
(item: Item) -> Item in
item.completed = false
return item
}
// -- this is the .map function
// print out the items in the array
print("Modified values")
for item in items {
print(item.name, item.completed)
}
and then, of course, call .reloadData()
on your table.
回答2:
Loop through items array and set property to false
for i in 0..<items.count {
items[i].completed = false
}
Once done, reload your tableview:
tableView.reloadData()
Addition if your question is how to do this from a separate VC, then I would suggest to learn delegation in Swift, here is a post
回答3:
There is a function to execute a closure for each item of the array
items.forEach{ $0.completed = false }
tableView.reloadData()
来源:https://stackoverflow.com/questions/46717778/change-bool-status-for-all-objects-of-all-cells-in-the-tableview