Reusing cell doesn't work well - TableView

前端 未结 6 1876
余生分开走
余生分开走 2021-01-27 12:35

I have a problem about my cell\'s button. In my tableView each row is composed by: an image, some labels and a button. The button has a checkmark image. When it is clicked, the

6条回答
  •  面向向阳花
    2021-01-27 12:56

    UITableViewCell is reusable. You can't store state of view in cell. You should setup cell in

    func tableView(UITableView, cellForRowAt: IndexPath)  
    

    method of your data source

    The easiest way to achieve that is to implement

    func tableView(UITableView, didSelectRowAt: IndexPath) 
    func tableView(UITableView, didDeselectRowAt: IndexPath)
    

    methods of UITableViewDelegate

    Then you can add/remove indexPath to some array in these methods and in cellForRowAtIndexPath setup cell.

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
            let cell = tableView.dequeueReusableCellWithIdentifier("YourTableViewCell") as! YourTableViewCell
    
            if array.contains(indexPath) {
             cell.checkBook.image = UIImage(named: "check")
            } else {
             cell.checkBook.image = UIImage(named: "uncheck")
            }
    
            return cell
    }  
    

提交回复
热议问题