Search code examples
swiftuitableviewcgaffinetransform

How to rotate all views in table view cells at once while scrolling?


I am trying to rotate all the UIViews in cells at once but i am unable to do it, so far i can rotate the UIViews present in the cells which are at top and bottom while scrolling up and down but the middle side of table view cell's UIViews are not rotating, they are only rotating when they are about to be dequeued.

Here's my source code :

   //
//  ViewController.swift
//  scrollIT
//
//  Created by AK on 10/2/19.
//  Copyright © 2019 AK. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    var indexPth: IndexPath!
    @IBOutlet weak var tableViewz: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
    }


}

extension ViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 23
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableViewz.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? RotationCell
        indexPth = indexPath
        return cell!
    }

    func rotationFunc(inIndexPath: IndexPath, someAngle: CGFloat) {
        if let cell = self.tableViewz.cellForRow(at: inIndexPath) as? RotationCell {
            DispatchQueue.main.async {
                cell.rotatableView.transform = CGAffineTransform(rotationAngle: someAngle)
                cell.rotatableView.layoutIfNeeded()
            }
        }
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let scrollOffset: CGPoint = scrollView.contentOffset
        print(scrollOffset)
        let degreesRotate: CGFloat = scrollOffset.y *  (CGFloat.pi / 180)
        rotationFunc(inIndexPath: indexPth , someAngle: degreesRotate)
    }



}

The output which i am getting is like this :

https://media.giphy.com/media/WTuteL5oD3HmEk4kjR/giphy.gif

Your time and help is greatly appreciated! Thanks! Let me know if i missed anything !


Solution

  • Try this, to do it for all cells:

    for eachIndexPath in tableViewz.indexPathsForVisibleRows {
    // do your rotation stuff here
    }