如何在表格视图中添加复选标记 swift

how to add checkmark in tableview swift

我试图在表格视图单元格上显示复选标记,但复选标记只是有时出现,当我滚动时它会消失。

代码下方:

 
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCellWithIdentifier("vvxxx12", forIndexPath: indexPath)
    
        // Configure the cell...
        
    cell.textLabel?.text = self.dataArray[indexPath.row] as? String //in dataArray values are stored
             

       if dataArray.containsObject(indexPath)
       {
            cell.accessoryType = .Checkmark
       }
       else {
            cell.accessoryType = .None
        }
       return cell
         }

        func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
            if let cell = tableView.cellForRowAtIndexPath(indexPath) {
                if cell.accessoryType == .Checkmark {
                    cell.accessoryType = .None
                   
                } else {
                    cell.accessoryType = .Checkmark
                   
                }
            }    
        }

cell.textLabel?.text = self.dataArray[indexPath.row] as? String

这表明 dataArray 包含字符串。

if dataArray.containsObject(indexPath)

这表明 dataArray 包含索引路径。这两个都不应该是真的。一个用于数据的数组是有意义的,另一个用于选定行或要检查的行的数组也有意义,但两者不是同一个数组。

可能发生的情况是:

  • 已选择行 - 然后更新单元格以包含复选标记附件
  • Table 滚动并调用 cellForRowAtIndexPath - dataArray 绝不会包含索引路径,因此总是清除附件。

您需要在选择行时更新模型,以存储所选行的索引路径,或更新模型对象上的选定标志。

只需在代码中进行以下更改,即可在滚动 tableview 时将复选标记保持在 tableview 中

结果:

它现在工作正常,有任何问题让我知道我一定会帮助你 out.Enjoy..

Swift 以下 3 个对我有用

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    yourtableView.cellForRow(at: indexPath as IndexPath)?.accessoryType = .checkmark
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    yourtableView.cellForRow(at: indexPath as IndexPath)?.accessoryType = .none
}