【问题标题】:Swift: UIAlert in function - Use of unresolved identifier 'present'Swift:函数中的 UIAlert - 使用未解析的标识符“存在”
【发布时间】:2017-08-17 17:27:29
【问题描述】:

我试图限制代码的显示,所以我只想调用包含两个字符串的函数,以用 1 行而不是 5 行更快地创建 uialert/

我遇到的错误

使用未解析的标识符“存在”

在线上

现在(警报,动画:真,完成:无)

// 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)
}

【问题讨论】:

  • 最常见的原因(我相信)是因为此代码/函数不在UIViewController 内。是这样吗?
  • 什么是self?它必须是UIViewController
  • 从哪里调用这个 sn-p ?
  • @dfd 正确,它只是一个我用来组织代码的 swift 文件,例如我称之为 System.showAlert("Title", "The Message")
  • 否则你可以传递你想要展示 UIViewController 的视图控制器

标签: ios swift uialertview


【解决方案1】:

在 cmets 中,您解释说这是一个独立的功能。如果您将其作为UIViewController 的扩展名,它应该可以工作,例如:

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)
    }

}

并在UIViewController 中调用它:

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

【讨论】:

  • 谢谢!如果我也想在系统类中调用它,因为写 showAlert("", "") 会给出错误Use of unresolved identifier 'showAlert'
  • 无论如何都要在 ViewController 之外调用它?
  • 由于presentUIViewController 中的一个方法,您需要扩展那个。正如所写,只要你称之为的 系统类UIViewController 的子类,你就很好。我不确定你到底在尝试什么,但它需要一个视图控制器在它上面呈现另一个——我相信你知道,因为它是基本的 MVC。接下来的第二条评论......
  • 如果你想做的是从视图控制器外部“呈现”某些东西,也许你可以使用NSNotification 来“告诉”视图控制器呈现某物。但请记住,尤其是在 iOS 中(没有“控制台应用程序”之类的东西),您几乎总是有一个视图 - 这意味着您有一个活动的视图控制器。 是你想要做任何“展示”的地方。尝试别的?我建议对此进行重构。
  • 例如,在我的 MainViewController 中,我运行从 system.swift(没有 viewcontroller)和 system.swift 中的 swift 类获取的代码,我有一个在 MainViewController 中运行的函数,但如果函数在系统有错误,显示一个 UIAlert 曾经 viewcontroller 在
猜你喜欢
  • 2015-05-13
  • 2016-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
相关资源
最近更新 更多