Reusing cell doesn't work well - TableView

前端 未结 6 1870
余生分开走
余生分开走 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 13:05

    Try my code . here selectindex is use for get selected cell index and selectedindex is NSMutableArray that i store all selected cell value.

    var selectindex : Int?
    var selectedindex : NSMutableArray = NSMutableArray()
    @IBOutlet var tableview: UITableView!
    
     func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
         let cell = tableView.dequeueReusableCellWithIdentifier("LikeCell", forIndexPath: indexPath)
         let like: UIButton = (cell.viewWithTag(2) as! UIButton)// like button
         let comment: UIButton = (cell.viewWithTag(3) as! UIButton) // comment button
         comment.setBackgroundImage(UIImage(named: "chat.png"), forState: UIControlState.Normal) // comment button set
         like.addTarget(self, action: #selector(self.CloseMethod(_:event:)), forControlEvents: .TouchDown)
         comment.addTarget(self, action: #selector(self.CloseMethod1(_:event:)), forControlEvents: .TouchDown)
    
         return cell
    }
    
    
    // This is my like button action method.
    @IBAction func CloseMethod(sender: UIButton, event: AnyObject) {
    
            let touches = event.allTouches()!
            let touch = touches.first!
            let currentTouchPosition = touch.locationInView(self.tableview)
            let indexPath = self.tableview.indexPathForRowAtPoint(currentTouchPosition)!
            selectindex = indexPath.row
            if selectedindex.containsObject(selectindex!) {
                 sender.setBackgroundImage(UIImage.init(named: "like (1).png"), forState: .Normal)
                 selectedindex.removeObject(selectindex!)
            }else{
                 sender.setBackgroundImage(UIImage.init(named: "like.png"), forState: .Normal)
                 selectedindex.addObject(selectindex!)
            }
    
    }
    

提交回复
热议问题