如何从UITableViewCell的UIContextualAction中显示弹出式UIAlertController?

时间:2018-10-22 18:02:01

标签: ios swift uitableview uicontextualaction

我想通过UITableViewCell中的UIContextualAction“按钮”呈现一个UIAlertController。我的问题是如何为特定的选定动作设置sourceRect?我认为这是可能的,当您在单元格上向左滑动时,iOS Mail应用程序允许您选择更多选项的方式(见图)。 enter image description here

1 个答案:

答案 0 :(得分:2)

设置动作时,它具有一个view参数。使用它来设置操作表。

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])
}

这当然仅在iPad上有效,因为在iPhone上,警报将从屏幕底部显示。