Search code examples
iosswiftuitableviewswift3uipopovercontroller

Swift 3: popover connection from button inside dynamic uitableviewcell to uiviewcontroller


Hello I'm trying to connect a viewcontroller with a uibutton inside a table view cell as a popover connection. I have a small view controller with 2 buttons inside which should be my popover. And I have a tableview with many many cells and buttons inside those cells. When the user clicks on a specific button I want to open a popover with a anchor on the clicked button like the default behavior of a popover connection on static content.

But when dealing with dynamic content I'm getting this error in my storyboard: Couldn't compile connection ...

Here is a little sample of what I'm trying to do and the error I get: enter image description here

I don't want to use dirty hacks like hidden 1 px buttons and something like this. I tried to create a custom segue but it's also not working good.

So what is the best way to achieve this?

This is how this example looks like as code:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CustomTableViewCell

        let button = cell.customButton

        return cell
    }

}


import UIKit

class CustomTableViewCell: UITableViewCell {

    @IBOutlet weak var customButton: UIButton!

    @IBAction func buttonTapped(_ sender: Any) {


    }

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

}

Solution

  • If your popover view is only with buttons, you can use UIAlertController, but the arrow would only appear in iPad

    @IBAction func buttonTapped(_ sender: Any) {
    
    let alertVC = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    alertVC.modalPresentationStyle = .popover
    //setup
    if let popoverController = alertVC.popoverPresentationController  {
            popoverController.permittedArrowDirections = .any
            popoverController.sourceView = self
            popoverController.sourceRect = self.bounds
        }
    }
    tableVC.present(alertVC, animated: true, completion: nil)