【问题标题】:Passing the function of the UIAlertAction to the UIAlertController extension将 UIAlertAction 的函数传递给 UIAlertController 扩展
【发布时间】:2019-08-26 15:28:57
【问题描述】:

我想要一个基本的 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
}

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

    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)

    }

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

【问题讨论】:

  • 当警报动作触发时,警报已被系统解除,您无需执行任何操作。
  • @Gereon 谢谢,其他功能怎么样?例如,如果我想要 2 个按钮,一个关闭,另一个执行其他操作?
  • 警报中的所有按钮都将关闭。

标签: ios swift uialertcontroller


【解决方案1】:

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($0)}
        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)
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 2020-11-01
    • 2018-04-26
    相关资源
    最近更新 更多