You could use notifications, as pointed out in the comments, but I would do something else.
1. In your custom cell class, I would add a property called parentVC
of type UIViewController
:
class YourTableViewCell: UITableViewCell {
var parentVC: UIViewController!
...
}
2. Then, when you are dequeueing the cell, I would set the cell's parentVC
to self
, like so:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: "YourCellIdentifier") as! YourTableViewCell
//`self` is the view controller that the cell's table view is held in
cell.parentVC = self
return cell
}
3. Finally, whenever your custom cell's button is clicked, simply present the alert controller from parentVC
:
class YourTableViewCell: UITableViewCell {
var parentVC: UIViewController!
@IBAction func customButtonPressed(_ sender: Any) {
let alertController = UIAlertController(title: "Your alert title.", message: "Your alert message.", preferredStyle: .alert)
parentVC.present(alertController, animated: true, completion: nil)
}
...
}
Another variation (as suggested by rmaddy)
You could simply change the button within your UITableViewCell
to recursively check the next responder until it is of type UIViewController
.
First add the following extension to UIView
. This will find the UIView
's parent view controller:
extension UIView {
var parentViewController: UIViewController? {
var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.next
if let viewController = parentResponder as? UIViewController {
return viewController
}
}
return nil
}
}
You could simply change the button within your UITableViewCell
to recursively check the next responder until it is of type UIViewController
. Once you find this UIViewController
, you can have it present the UIAlertController
, or any other view controller:
Source: Given a view, how do I get its viewController?
Once you find this UIViewController
, you can have it present the UIAlertController
, or any other view controller:
class YourTableViewCell: UITableViewCell {
...
@IBAction func customButtonPressed(_ sender: Any) {
let alertController = UIAlertController(title: "Your alert title.", message: "Your alert message.", preferredStyle: .alert)
guard let parentVC = self.parentViewController else { return }
parentVC.present(alertController, animated: true, completion: nil)
}
...
}