How to get UITableView from UITableViewCell? How to get UITableView from UITableViewCell? ios ios

How to get UITableView from UITableViewCell?


To avoid checking the iOS version, iteratively walk up the superviews from the cell's view until a UITableView is found:

id view = [tableViewCellInstance superview];while (view && [view isKindOfClass:[UITableView class]] == NO) {    view = [view superview]; }UITableView *tableView = (UITableView *)view;


In iOS7 beta 5 UITableViewWrapperView is the superview of a UITableViewCell. Also UITableView is superview of a UITableViewWrapperView.

So for iOS 7 the solution is

UITableView *tableView = (UITableView *)cell.superview.superview;

So for iOSes up to iOS 6 the solution is

UITableView *tableView = (UITableView *)cell.superview;


Swift 5 extension

Recursively

extension UIView {    func parentView<T: UIView>(of type: T.Type) -> T? {        guard let view = superview else {            return nil        }         return (view as? T) ?? view.parentView(of: T.self)    }}extension UITableViewCell {    var tableView: UITableView? {        return parentView(of: UITableView.self)    }}

Using loop

extension UITableViewCell {    var tableView: UITableView? {        var view = superview        while let v = view, v.isKind(of: UITableView.self) == false {            view = v.superview        }        return view as? UITableView    }}