我的表视图中的每个单元格都有各种属性:
class: Item
// properties
var name: String
var photo: UIImage?
var category: String
var instructions: String
var completed = false
(所有内容也已初始化)
我的表视图数组是:
items = [Item]()
当 Item.complete 为 true 时,单元格将有一个复选标记附件,否则它将具有 .none
我想使用 UIButton(在单独的 VC 中)使 Item.complete = false 对于表视图中的每个单元格,从而删除所有复选标记并基本上重置数据。
我的项目:Item 数组是可变的,因为用户可以选择添加或删除数组中的任何行。
我希望 UIButton(位于单独选项卡中的单独 VC 上)转到表视图并进行更改。
如何将每个单元格 .complete 属性更改为与 UIButton 相等的 false,以便我可以删除每个单元格上的复选标记?
有一个函数为数组的每个项目执行闭包
items.forEach{ $0.completed = false }
tableView.reloadData()
您也可以使用 .map
函数。
您可以直接在 Playground 页面中运行以下命令:
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)
}
然后,当然,打电话给你桌子上的.reloadData()
。
遍历项数组并将属性设置为 false
for i in 0..<items.count {
items[i].completed = false
}
完成后,重新加载表视图:
tableView.reloadData()
另外,如果你的问题是如何从一个单独的VC做到这一点,那么我建议在Swift中学习委托,这里有一篇文章