使用表格视图(XCode 9,Swift 4)时,我遇到了一个非常具体的问题。我想做的是,创建一个名为foodDetailInfoArray的数组,并在用户手动选择的表格单元格中使用foodName标签的文本值。目前,虽然.setSelected方法可以根据需要更改单元格的UI,但它并不能帮助我正确记录foodName.text值。问题在于,即使在滚动表视图时也会记录文本值,并且数组值也会被替换。以下是代码和打印输出的示例。
var foodDetailInfoArray: [String] = [] @IBOutlet var unselectedCell: UIView! @IBOutlet var foodName: UILabel! @IBOutlet var carbonValue: UILabel! override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state if selected == true { self.unselectedCell.backgroundColor = UIColor.init(red: 4/255, green: 206/255, blue: 132/255, alpha: 1) self.foodName.textColor = UIColor.white self.carbonValue.textColor = UIColor.white foodDetailInfoArray.append(foodName.text!) } else { self.unselectedCell.backgroundColor = UIColor.clear self.foodName.textColor = UIColor.black self.carbonValue.textColor = UIColor.black } print(foodDetailInfoArray) }
print语句为我提供了这样的结果:(这是什至没有选择单元格,而我只是滚动表格视图的时候。)
["pepper"] ["pasta"] ["pasta", "pepper"] ["pepper"] ["pepper", "pasta"] ["stir-fry"] ["stir-fry", "stir-fry"] ["vegetable"] ["vegetable", "vegetable"]
而我理想的情况是(按一下包含给定foodName的单元格的顺序):
["pasta"] ["pasta", "pepper"] ["pasta", "pepper", "tomato"] ["pasta", "pepper", "tomato", "stir-fry"]
如果取消选择某个单元格,则必须删除该名称,即,如果取消选择tomato,则数组为
["pasta", "pepper", "stir-fry"]
... 等等
PS:我不是专业的程序员,而是最近自学成才,所以请让我知道问题是否仍然不清楚。
我将通过视图控制器处理单元格的选择和取消选择,因此您也可以foodDetailInfoArray
更好地使用它。借助此答案,您可以像这样进行操作:
import UIKit class ViewController: UITableViewController { // example data let names = [ "pepper", "pasta", "stir-fry", "vegetable"] var foodDetailInfoArray: [String] = [] override func viewDidLoad() { super.viewDidLoad() // allow multiselection tableView.allowsMultipleSelection = true } // MARK: UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: "cell") cell.textLabel?.text = names[indexPath.row] // Don't show highlighted state cell.selectionStyle = .none return cell } // MARK: UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // also do your UI changing for the cell here for selecting // Add your food detail to the array foodDetailInfoArray.append(names[indexPath.row]) } override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { // also do your UI changing for the cell here for deselecting // Remove your food detail from the array if it exists if let index = foodDetailInfoArray.index(of: names[indexPath.row]) { foodDetailInfoArray.remove(at: index) } } }
结果