如何根据所选单元格在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
只是一个类别字符串数组,如hello
, world
和stackoverflow
。 我们检查selectedCategories
数组是否包含当前单元格/行的类别字。
假设我们正在设置的单元格有一个hello
类别, selectedCategories
确实包含它。 这意味着selected
bool设置为true。
然后我们将category
和selected
值传递给单元子类’load方法,在该load方法中,您可以将单元格的标题文本设置为category
并且可以检查selected
是否为true,如果为true,则可以显示已选中盒子UI。
- 检测用户是否退还了应用购买项目中的“耗材”(应用购买系统中的Appleapp store)
- 将UIImage编码为Base64string时,传输到服务器时不起作用
- WatchOS 3 WKApplicationRefreshBackgroundTask didReceiveChallenge
- sortinganyobject Swift 3的数组
- 在iOS中使用sendAsynchronousRequest:request API处理401状态码
- 不兼容的指针types,用'BaseClass *'types的expression式初始化'SubClass * __ strong'
- build立静态库
- 为iOS提供自动续订订阅
- 什么是带有cocoapods,swift 3和Xcode 8的ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES