0

I had created extension :

 public extension UITableViewCell {
        /// Generated cell identifier derived from class name
        static func cellIdentifier() -> String {
            return String(describing: self)
        }
      
        var indexPath:IndexPath?{
               return tableView?.indexPath(for: self)
        }
      
        var tableView: UITableView? {
               var view = superview
               while let v = view, v.isKind(of: UITableView.self) == false {
                   view = v.superview
               }
               return view as? UITableView
        }
    }

I am trying to use extension in uitableviewcell class :

func setup(viewModel: ViewModelClass) {       
        if indexPath != nil {
            print("indexpath") 
        }else {
            print("nil")  // But it always gives nill.
        }
}

I want to fetch section and row for index in uitableviewcell.

  • How do you call `setup(viewModel:`? – aheze Nov 17 '20 at 17:13
  • Most likely the cell is not part of a `UITableView` yet. By the way, you should probably use `is` instead of `isKind(of:)`. – Sulthan Nov 17 '20 at 17:35
  • setup() is protocol method which is called from cellForRowAt indexPath – Sweta Dodiya Nov 17 '20 at 17:38
  • 1
    This kind of *retain cycle* is pretty weird. The cell is part of the table view, not the other way round. And the view hierarchy math to get the table view reference is even weirder. – vadian Nov 17 '20 at 17:53

1 Answers1

1

Take a look at this extension. I use this in project to get indexPath and tableView in UITableViewCell subclasses and it works totally fine.

private extension UIResponder {
    func next<T: UIResponder>(_ type: T.Type) -> T? {
        return next as? T ?? next?.next(type)
    }
}

extension UITableViewCell {

    var tableView: UITableView? {
        return next(UITableView.self)
    }

    var indexPath: IndexPath? {
        return tableView?.indexPath(for: self)
    }
}