iosswiftuitableviewuiviewcontrolleruipopover

How to use UITableViewCell's accessoryButton as anchor for a Popover


I tried to use the accessoryButton of the UITableViewCell as the anchor of a Popover, but couldn't connect it using the storyboard. Programmatically I tried using the accessoryButtonTappedForRowWith function, this didn't work either. How can I connect it?


Solution

  • If your class is subclass of UITableViewController then use:

    override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
        print(indexPath.row)
    }
    

    Check example code:

    class ViewController: UITableViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
        }
    
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            cell.textLabel?.text = "\(indexPath.row)"
    
            cell.accessoryType = UITableViewCellAccessoryType.detailButton
            return cell
        }
    
        override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
            print(indexPath.row)
        }
    
        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 10
        }
    }
    

    And if it's a subclass of UIViewController then you don't need override before that method so it will be:

    func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
        print(indexPath.row)
    }
    

    And don't forget to connect UITableViewDataSource and UITableViewDelegate of your table view with your ViewController in this case.