我正在尝试从中捕获所选项目UITableView并将其保存到新数组中。下面的代码通过在点击行时添加项目来创建新数组,而当取消选择行时,它不执行的操作是删除项目。
newFruitList当UITableView取消选择a中的行时,如何从中删除项目?
还是更好的方法是,仅生成一个选定项目的数组的正确方法是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)
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过获取列表中该项目的索引来检查newFruitList是否包含要添加的项目。
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)")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
944 次 |
| 最近记录: |