jat
jat

Reputation: 357

Swift - UITableView Cell animation on selection

I am animating a tableView cell selection from with the didSelectRow at method, which is working. My code is as follows :

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

let cell = tableView.cellForRow(at: indexPath)
            
            UIView.animate(withDuration: 0.2, animations: {
                
                cell!.transform = CGAffineTransform(scaleX: 0.97, y: 0.97)
                
            }, completion: { finished in
                
                UIView.animate(withDuration: 0.2) {
                    
                    cell!.transform = .identity
                }
                
            })

}

I'd like to be able to put this in the custom class file for the cell but don't know where to start. Is this possible ?

Thankyou

Upvotes: 2

Views: 2558

Answers (1)

singh.jitendra
singh.jitendra

Reputation: 500

I think you can use func setSelected(_ :animated:)

First, you will have to create a subclass of UITableViewCell.

suppose I created a Class name TempTableViewCell, In this, we do have a predefined function override func setSelected(_ selected: Bool, animated: Bool).

Here Selected is the value for if the cell is selected or not. So you can have your code in this function like below.

Example

    class TempTableViewCell: UITableViewCell {
    
    override func awakeFromNib() {
        super.awakeFromNib()
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        if selected{
            UIView.animate(withDuration: 0.2, animations: {
                self.transform = CGAffineTransform(scaleX: 0.97, y: 0.97)
            }, completion: { finished in
                UIView.animate(withDuration: 0.2) {
                    self.transform = .identity
                }
            })
        }
    }
    
}

And to use it in the cell follow the below code,

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: TempTableViewCell.self), for: indexPath)
        return cell
    }

Upvotes: 7

Related Questions