Delegate Method to UItableViewCell Swift

前端 未结 3 711
Happy的楠姐
Happy的楠姐 2021-01-25 03:11

I have a Social Network Feed in form UItableView which has a cell. Now each cell has an image that animates when an even is triggered. Now, This event is in form of a string, wi

3条回答
  •  迷失自我
    2021-01-25 03:48

    Try something like this:

    Define your delegate protocol:

    protocol CustomCellDelegate: class {
        func animationStarted()
        func animationFinished()
    }
    

    Define your CustomCell. Extremely important to define a weak delegate reference, so your classes won't retain each other.

    class CustomCell: UITableViewCell {
        // Don't unwrap in case the cell is enqueued!
        weak var delegate: CustomCellDelegate?
    
        /* Some initialization of the cell */
    
        func performAnimation() {
            delegate?.animationStarted()
            UIView.animate(withDuration: 0.5, animations: {
                /* Do some cool animation */
            }) { finished in
                self.delegate?.animationFinished()
            }
        }
    }
    

    Define your view controller. assign delegate inside tableView:cellForRowAt.

    class ViewController: UITableViewDelegate, UITableViewDataSource {
    
        /* Some view controller customization */
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: CustomCell.self)) as? CustomCell
            cell.delegate = self
            cell.performAnimation()
            return cell
        }
    }
    

提交回复
热议问题