简体   繁体   English

在 swift 中的 scope 错误中找不到“UIAlertController”?

[英]Cannot find 'UIAlertController' in scope error in swift?

Why I am getting Cannot find 'UIAlertController' in scope?为什么我Cannot find 'UIAlertController' in scope? error if i write alert function in separate swift file or if i use extension its not coming to another viewcontroller why?如果我在单独的 swift 文件中写入警报 function 或者如果我使用扩展名,它不会进入另一个视图控制器,为什么会出错?

code:代码:

 func showAlert(title: String, message: String) {
  let alertController = UIAlertController(title: title, message:
    message, preferredStyle: .alert)
  alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: {action in
  }))
  self.present(alertController, animated: true, completion: nil)
}

error:错误:

Cannot find 'UIAlertController' in scope,在 scope 中找不到“UIAlertController”,

Cannot find 'UIAlertAction' in scope在 scope 中找不到“UIAlertAction”

Cannot find 'self' in scope在 scope 中找不到“自我”

Probably you forgot this in your viewController:可能您在 viewController 中忘记了这一点:

import UIKit

so your file has no idea what UIAlertController or UIAlertAction is所以你的文件不知道UIAlertControllerUIAlertAction是什么

if you want to create an alert view controller to be used across multiple UIViewController you can do this:如果您想创建一个警报视图 controller 以跨多个 UIViewController 使用,您可以这样做:

import UIKit

class CustomAlertController: NSObject {
    
    let message:String?
    let title:String?
    
    init(title:String, message:String) {
        self.message = message
        self.title = title
    }
    

    func showAlert()->UIAlertController {
        let alertController = UIAlertController(title: self.title, message: self.message, preferredStyle: .alert)
        // you can further customize your buttons, buttons' title etc 
        alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: {action in
        }))
        return alertController
    }
    
}

then your view controllers然后你的视图控制器

import UIKit
class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let alert = CustomAlertController(title: "Hello", message: "My message to the world")
        DispatchQueue.main.async {
        self.present(alert.showAlert(), animated: true, completion: nil)
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM