所以我在 swift 和 Xcode 中构建了我的单 View 应用程序。我所有的代码都在一个文件中,主要的 ViewController.swift
随着代码变得越来越大,为了让事情变得更容易,我已经开始将这些方法移动到一个单独的 swift 文件中,以保持事情井井有条 - ClipManager.swift
.
我有 3 种方法都使用 notifyUser
调用 UIAlertController
的方法.
所以我把这个方法移到了同一个文件中,ClipManager.swift
但是现在在当前 ViewController 中调用这些方法时我的警报没有显示 - ViewController.swift
因为方法在单独的文件中。
首先是我使用 UIAlert 的方法
////Located in ClipManager.swift
class ClipManager: UIViewController {
func notifyUser(title: String, message: String) -> Void
{
let alert = UIAlertController(title: title,
message: message,
preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "OK",
style: .Cancel, handler: nil)
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true,
completion: nil)
}}
我的方法调用来自 ViewController.swift
class ViewController: UIViewController {
///// In ViewController.swift (where I want the Alert to show)
let SavedRecord = MyClipManager.SaveMethod(publicDatabase!, myRecord: record)
SaveMethod
的代码位于ClipManager.swift
func SaveMethod(publicDatabase: CKDatabase, myRecord:CKRecord ) -> CKRecord {
publicDatabase.saveRecord(myRecord, completionHandler:
({returnRecord, error in
if let err = error {
//// **** Notify called here *****
self.notifyUser("Save Error", message:
err.localizedDescription)
} else {
dispatch_async(dispatch_get_main_queue()) {
self.notifyUser("Success",
message: "Record saved successfully")
}
}
}))
return myRecord
}
我猜我的警报没有显示是因为它们实际上是在 ClipManager.swift
上触发的这不在 View 中。
我在这里有什么选择,移动NotifyUser
返回ViewController.swift
并在 ClipManager.swift
中创建和对象在我位于那里的方法中调用它?
或者有没有办法将这些警报传递给显示的 View ?
最佳答案
您好,我将如何代替您。
对于我的 ClipManager 类,它将从 NSObject 扩展。不需要 UIView Controller
类应该是这样的
class ClipManager: NSObject {
func notifyUser(title: String, message: String) -> Void
{
let alert = UIAlertController(title: title,
message: message,
preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "OK",
style: .Cancel, handler: nil)
alert.addAction(cancelAction)
UIApplication.sharedApplication().keyWindow?.rootViewController!.presentViewController(alert, animated: true,
completion: nil)
}
}
为了呈现 alertView,我使用应用程序的 rootViewController
无需在您的 ViewController 类中进行更改。
让我知道它是否适合你:)
关于ios - 移动到另一个 swift 文件时 UIAlertController 不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34935307/