Swift: UIAlert in function - Use of unresolved identifier 'present'

£可爱£侵袭症+ 提交于 2021-02-05 10:52:27

问题


I'm trying to limit the show of code so I just want to call function containing two strings to create a uialert faster with 1 line instead of 5/

The error I'm getting

Use of unresolved identifier 'present'

at the line

present(alert, animated: true, completion: nil)

// Controlling Alerts for Errors
func showAlert(titleString: String, messageString: String) {

 // Alert to go to Settings
 let alert = UIAlertController(title: titleString, message: messageString, preferredStyle: .alert)

 alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: { _ in
     alert.dismiss(animated: true, completion: nil)
 }))

 self.present(alert, animated: true, completion: nil)
}

回答1:


In the comments, you explained that this is a stand-alone function. It should work if you make it an extension to UIViewController, for instance:

extension UIViewController {
    public func showAlert(_ title:String, _ message:String) {
        let alertVC = UIAlertController(
            title: title,
            message: message,
            preferredStyle: .alert)
        let okAction = UIAlertAction(
            title: "OK",
            style: .cancel,
            handler: { action -> Void in
        })
        alertVC.addAction(okAction)
        present(
            alertVC,
            animated: true,
            completion: nil)
    }

}

And to call it in a UIViewController:

showAlert(
    "Could Not Send Email", 
    "Your device could not send e-mail.  Please check e-mail configuration and try again."
)


来源:https://stackoverflow.com/questions/45741521/swift-uialert-in-function-use-of-unresolved-identifier-present

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!