簡體   English   中英

在 swift 中的 scope 錯誤中找不到“UIAlertController”?

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

為什么我Cannot find 'UIAlertController' in scope? 如果我在單獨的 swift 文件中寫入警報 function 或者如果我使用擴展名,它不會進入另一個視圖控制器,為什么會出錯?

代碼:

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

錯誤:

在 scope 中找不到“UIAlertController”,

在 scope 中找不到“UIAlertAction”

在 scope 中找不到“自我”

可能您在 viewController 中忘記了這一點:

import UIKit

所以你的文件不知道UIAlertControllerUIAlertAction是什么

如果您想創建一個警報視圖 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
    }
    
}

然后你的視圖控制器

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