如何将函数作为参数传递给警报措施?

时间:2018-10-22 14:36:14

标签: ios swift uialertview

这是我的全局功能。我想将动作作为另一个功能传递。因此,请给我解决方案。

showAlert(title: "Title", message: "Hello", viewController: self, action: self.deactivateViewOne())

 func showAlert(title: String, message: String, viewController: UIViewController, action: -----){
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
        alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style:   UIAlertAction.Style.cancel, handler: nil))
        alert.addAction(UIAlertAction(title: NSLocalizedString("Deactivate", comment: ""), style:   UIAlertAction.Style.cancel, handler: { (alert) in
            action
            }))
        viewController.present(alert, animated: true, completion: nil)
        let subview = (alert.view.subviews.first?.subviews.first?.subviews.first!)! as UIView
        subview.layer.cornerRadius = 10
        subview.backgroundColor = Common.backgroundColor
        subview.layer.borderWidth = 0.5
        subview.layer.borderColor = Common.fontColor.cgColor
    }
 func deactivateViewOne() {
        self.viewOne.layer.borderColor = Common.greyColor.cgColor
        self.viewOneStartTime.textColor = Common.greyColor
        self.viewOneStopTime.textColor = Common.greyColor
        self.ViewOneHeatLabel.textColor = Common.greyColor
        self.ViewOneUhrLabel.textColor = Common.greyColor
        self.ViewOneDashLabel.textColor = Common.greyColor
        self.viewOneStartTime.text = "--:--"
        self.viewOneStopTime.text = "--:--"
    }

1 个答案:

答案 0 :(得分:1)

只使用闭包。

dialog

并使用:

func showAlert(title: String, message: String, viewController: UIViewController, action: @escaping () -> ()) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
    alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style:   UIAlertAction.Style.cancel, handler: nil))
    alert.addAction(UIAlertAction(title: NSLocalizedString("Deactivate", comment: ""), style:   UIAlertAction.Style.default, handler: { (alert) in
        action()
    }))
    viewController.present(alert, animated: true, completion: nil)
    let subview = (alert.view.subviews.first?.subviews.first?.subviews.first!)! as UIView
    subview.layer.cornerRadius = 10
    subview.backgroundColor = Common.backgroundColor
    subview.layer.borderWidth = 0.5
    subview.layer.borderColor = Common.fontColor.cgColor
    }