我正在尝试从 a 中捕获选定的项目UITableView
并将它们保存到一个新数组中。以下代码通过在点击行时添加项目来创建新数组,但它不会在取消选择行时删除项目。
如何从列表中删除项目newFruitList
当a中的一行UITableView
被取消选择?
或者更好的是,生成仅包含所选项目的数组的正确方法是什么?UITableView
?
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let fruits = ["Apples", "Oranges", "Grapes", "Watermelon", "Peaches"]
var newFruitList:[String] = []
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fruits.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = fruits[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
newFruitList.append(fruits[indexPath.row])
print("New List: \(newFruitList)")
}
@IBAction func makeSelection(_ sender: Any) {
tableView.allowsMultipleSelectionDuringEditing = true
tableView.setEditing(true, animated: false)
}
}
您只需检查是否新水果清单包含您想要通过获取列表中该项目的索引来添加的项目。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
newFruitList.append(fruits[indexPath.row])
print("New List: \(newFruitList)")
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let index = newFruitList.index(of: fruits[indexPath.row]) {
newFruitList.remove(at: index)
}
print("New List: \(newFruitList)")
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)