如何根据所选单元格在tableview中设置启用的checkimage

我从服务器获取以前选择的类别列表。 比如说我从服务器获取的example.cateogrylist是以下格式

categoryid : 2,6,12,17 

现在我需要做的是想在我的tableview中启用基于此类别列表的复选标记,为此我将此列表转换为[Int]数组,如下所示:

 func get_numbers(stringtext:String) -> [Int] { let StringRecordedArr = stringtext.components(separatedBy: ",") return StringRecordedArr.map { Int($0)!} } 

在viewDidLoad()中:

  selectedCells = self.get_numbers(stringtext: UpdateMedicalReportDetailsViewController.catId) print(myselection) 

虽然打印它给我这样的结果: [12,17,6,8,10]

我想基于这个数组启用checkimage。我尝试了一些代码,同时打印它给我正确的结果,就像我在发布时选择的类别一样,我能够获取它,但未能将这个选择放回到tableview中。要求:当我打开此页面时,它应该显示基于我从服务器获取的类别列表的选择。

 var selectedCells : [Int] = [] func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell1 = table.dequeueReusableCell(withIdentifier: "mycell") as! catcell cell1.mytext.text = categoriesName[indexPath.row] if UpdateMedicalReportDetailsViewController.flag == 1 { selectedCells = self.get_numbers(stringtext: UpdateMedicalReportDetailsViewController.catId) cell1.checkimage.image = another print(selectedCells) } else { selectedCells = [] cell1.checkimage.image = myimage } return cell1 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = table.cellForRow(at: indexPath) as! catcell cell.checkimage.image = myimage if cell.isSelected == true { self.selectedCells.append(indexPath.row) cell.checkimage.image = another } } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { let cell = table.cellForRow(at: indexPath) as! catcell if cell.isSelected == false { self.selectedCells.remove(at: self.selectedCells.index(of: indexPath.row)!) cell.checkimage.image = myimage } } 

输出:

在此处输入图像描述

这是大多数应用程序中非常常见的用例。 我假设你有一个所有类别的数组,然后是一系列选定的类别。 您需要做的是在cellForRowAtIndexPath ,检查“所有类别”数组中当前索引路径行的相应类别是否也出现在“所选类别”数组中。 你可以通过比较id等来做到这一点。

如果您有匹配项,那么您就知道需要选择/检查该单元格。 一个干净的方法是给你的单元子类一个自定义加载方法,你可以传递一个标记选择/检查。

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = table.dequeueReusableCell(withIdentifier: "mycell") as! catcell let category = self.categories[indexPath.row] // Let's say category is a string "hello" Bool selected = self.selectedCategories.contains(category) cell.load(category, selected) return cell } 

因此,使用上面的代码,我们可以说categories只是一个类别字符串数组,如helloworldstackoverflow 。 我们检查selectedCategories数组是否包含当前单元格/行的类别字。

假设我们正在设置的单元格有一个hello类别, selectedCategories确实包含它。 这意味着selected bool设置为true。

然后我们将categoryselected值传递给单元子类’load方法,在该load方法中,您可以将单元格的标题文本设置为category并且可以检查selected是否为true,如果为true,则可以显示已选中盒子UI。