gpt4 book ai didi

ios - 将 UIAlertAction 的功能传递给 UIAlertController 扩展

转载 作者:搜寻专家 更新时间:2023-11-01 06:50:31 24 4
gpt4 key购买 nike

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

}

关于ios - 将 UIAlertAction 的功能传递给 UIAlertController 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57660851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com