How to show an alert from another class in Swift?

前端 未结 3 507
我寻月下人不归
我寻月下人不归 2021-02-02 02:11

I have a main class, AddFriendsController, that runs the following line of code:

ErrorReporting.showMessage(\"Error\", msg: \"Could not add student          


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-02 03:09

    Actually, in my opinion the view controller presenting operation should be done on the UIViewController instance, not in a model class.

    A simple workaround for it is to pass the UIViewController instance as a parameter

    class ErrorReporting {
        func showMessage(title: String, msg: String, `on` controller: UIViewController) {
            let alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
            controller.presentViewController(alert, animated: true, completion: nil)
        }
    }
    

    And call it like below

    ErrorReporting.showMessage("Error", msg: "Could not add student to storage.", on: self)
    

提交回复
热议问题