user3766930 user3766930 - 2 months ago 8
Swift Question

is there a way of refreshing the whole UITableView through a button that is in one of the cells?

I have a dynamically generated UITableView with many dynamic

UITableViewCells
and one static
UITableViewCell
.

The static one has a button and I want to refresh the whole table view when user presses it.

My code attached to the cell is simple:

class MyStaticCell: UITableViewCell {

@IBOutlet weak var sendCommentButton: UIButton!

@IBAction func sendCommentButtonAction(sender: AnyObject) {

//from here I want to refresh the table

}
}


How can I refresh the parent table from that button? In the class
MyStaticCell
I don't have any instance of the table, so that's my problem for now :|

Answer

You could access the tableView using superview.

class MyStaticCell: UITableViewCell {

    @IBOutlet weak var sendCommentButton: UIButton!

    @IBAction func sendCommentButtonAction(sender: AnyObject) {

        (superview as? UITableView)?.reloadData()
    }
}

This isn't as stable as it could be so maybe consider this extension:

extension UIResponder {

    func nextResponder<T: UIResponder>(ofType type: T.Type) -> T? {

        switch nextResponder() {

        case let responder as T:
            return responder

        case let .Some(responder):
            return responder.nextResponder(ofType: type)

        default:
            return nil
        }
    }
}

It allows you to find the next parent of a particular type, in the cells case, a UITableView.

class MyStaticCell: UITableViewCell {

    @IBOutlet weak var sendCommentButton: UIButton!

    @IBAction func sendCommentButtonAction(sender: AnyObject) {

        nextResponder(ofType: UITableView.self)?.reloadData()
    }
}