将 UIAlertAction 的功能传递给 UIAlertController 扩展

Passing the function of the UIAlertAction to the UIAlertController extension

我想要一个基本的 UIAlertController,我想通过传递按钮及其闭包在不同的 类 中使用它。为此,我从 UIAlertController 创建了一个扩展,如下所示:

extension UIAlertController {
    func showAlert(buttons: [ButtonsAction]?) -> UIAlertController {
        let alert = self
        guard let alertButtons = buttons else {
            return alert
        }
        for button in alertButtons {
            let alertAction = UIAlertAction(title: button.title, style: button.style, handler: {action in
                button.handler()
            })
            alert.addAction(alertAction)
        }

        return alert
    }
}

对于我的按钮,我有一个结构:

struct ButtonsAction {
    let title: String!
    let style: UIAlertAction.Style
    let handler: () -> Void
}

在我的一个 viewController 中,我有一个显示警报的功能。在该功能中,我有一个标题和一条消息,然后我想要 1 个按钮来关闭警报。函数是这样的:

    func fetchFaild(title: String, message: String) {
        let buttons = ButtonsAction.init(title: "cancel", style: .cancel, handler: {action in
            //here I want to dissmiss the alert I dont know how
        })

        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert).showAlert(buttons: buttons)
        alert.show(self, sender: nil)

    }

我在向警报添加按钮时遇到问题,我不知道如何向按钮添加操作。 我知道这不是这里的最佳做法。如果有人知道可以帮助我实现这一目标的示例或教程,我将非常感激。

UIViewController 的扩展可能是更合理的解决方案,ButtonsAction 结构似乎是多余的。

 extension UIViewController {
    func showAlert(title: String, message: String, actions: [UIAlertAction], completion: (() -> Void)? = nil)  {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        actions.forEach{alertController.addAction([=10=])}
        self.present(alertController, animated: true, completion: completion)
    }
}

class MyController : UIViewController {

    func fetchFailed(title: String, message: String) {
        let actions = [UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) in
            print("Cancel tapped")
        })]
       showAlert(title: title, message: message, actions: actions)
    }

}