Find out the parent view of a clicked button in swift Find out the parent view of a clicked button in swift ios ios

Find out the parent view of a clicked button in swift


Please try the following

sender.superview


I you don't want to create a custom class and also don't want to use accessibilityHin:

    func performAction(_ sender : AnyObject?){    let cell = sender?.superview??.superviewOfClassType(UITableViewCell.self) as! UITableViewCell    let tbl = cell.superviewOfClassType(UITableView.self) as! UITableView    let indexPath = tbl.indexPath(for: cell)     let myData = myDataArray[indexPath.row]    ...}


If you are looking for a specific parent in the view hierarchy or even in the parent controllers or any other responder, you can use this extension:

extension UIResponder {    func nextFirstResponder(where condition: (UIResponder) -> Bool ) -> UIResponder? {        guard let next = next else { return nil }        if condition(next) { return next }        else { return next.nextFirstResponder(where: condition) }    }}

Usage Example

The following returns the tableViewController that contains myButton. No matter how deep it is nested in views and subviews.

let tvc = myButton.nextFirstResponder { $0 is UITableViewController }


matomo