iosswiftuitableviewuicontextualaction

How to display a popover UIAlertController from a UITableViewCell's UIContextualAction?


I'd like to present a UIAlertController over a UIContextualAction 'button' in a UITableViewCell. My question is how to set the sourceRect for the specific selected action? I assume it's possible, the way the iOS Mail app allows you to select more options when you swipe left on a cell (see image). enter image description here


Solution

  • When you setup your action, it has a view parameter. Use that to setup the action sheet.

    override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let act1 = UIContextualAction(style: .normal, title: "Bar") { (action, view, completion) in
            completion(false)
        }
    
        let act2 = UIContextualAction(style: .normal, title: "Foo") { (action, view, completion) in
            let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
            alert.addAction(UIAlertAction(title: "Option 1", style: .default) { (action) in
                completion(true)
            })
            alert.addAction(UIAlertAction(title: "Option 2", style: .default) { (action) in
                completion(false)
            })
    
            // This sets up the alert to show next to the button
            alert.popoverPresentationController?.sourceView = view
            alert.popoverPresentationController?.sourceRect = view.bounds
    
            self.present(alert, animated: true, completion: nil)
        }
    
        return UISwipeActionsConfiguration(actions: [act1, act2])
    }
    

    Of course this only works on an iPad since on an iPhone the alert will show from the bottom of the screen.