ios – How to calculate the height of a cell in a table view in Swift?


I want to make a specific cell in my table view sticky, and for that, I’ve created a header that appears when the cell is about to disappear and stays at the top, something like this

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    
    let offsetY = scrollView.contentOffset.y



    
    if offsetY >= rectOfInfoCouponsAvailable  {
        if stickyHeaderView == nil {
            stickyHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 100))
            view.addSubview(stickyHeaderView!)
            configureStickyHeaderView()
        }
    } else {
       
        stickyHeaderView?.removeFromSuperview()
        stickyHeaderView = nil
    }
}

I’m currently assigning a constant value to rectOfInfoCouponsAvailable, but it doesn’t work well on all devices. I would like this value to be the height at which the specific cell I want becomes visible. How can I dynamically calculate this height based on the device or table view’s content?

I’ve tried using the following code but it doesnt work correctly because it always return 0:

let indexPath = IndexPath(row: 2, section: 0)  
if let rectForCell = tableView.rectForRow(at: indexPath) {
    let rectOfInfoCouponsAvailable = rectForCell.size.height
   
}

Any assistance or suggestions would be greatly appreciated. Thank you in advance for your help!

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img