ios - 如何创建可重用的 UIAlertcontroller?

标签 ios iphone swift uialertcontroller

我想为我的项目创建一个可重用的 UIAlertController 类。我尝试了以下代码。但我的警报没有显示。我的代码或任何代码帮助有什么问题。这是我的警报类

class AlertView: NSObject {

 class func showAlert(view: UIViewController , message: String){

        let alert = UIAlertController(title: "Warning", message: message, preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
        view.presentViewController(alert, animated: true, completion: nil)
    }
}

我在我的另一个 View Controller 中调用它

class ViewController: UIViewController {

  override func viewDidLoad() {
      super.viewDidLoad()
      AlertView.showAlert(self, message: "Test alert")
      // Do any additional setup after loading the view, typically from a nib.
   }
}

最佳答案

您可以使用 Anbu Karthiks 的答案。作为替代方案,我使用 Swift 2s 协议(protocol)扩展来显示警报。

import UIKit

protocol Alertable { }
extension Alertable where Self: UIViewController {

func showAlert(title title: String, message: String) {

    let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)

    let okAction = UIAlertAction(title: "OK", style: .Cancel) { _ in }
    alertController.addAction(okAction)

    DispatchQueue.main.async {       
       self.view?.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
    }
}

 func showAlertWithSettings(title title: String, message: String) {

    let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)

    let okAction = UIAlertAction(title: "OK", style: .Cancel) { _ in }
    alertController.addAction(okAction)

    let settingsAction = UIAlertAction(title: "Settings", style: .Default) { _ in
       guard let url = NSURL(string: UIApplicationOpenSettingsURLString) else { return }
        UIApplication.sharedApplication().openURL(url)
    }
    alertController.addAction(settingsAction)

    DispatchQueue.main.async {       
         self.view?.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
   }
}

现在在您需要显示警报的 viewController 中,您只需遵守协议(protocol)即可

class ViewController: UIViewController, Alertable { } 

然后像这样调用方法

showAlert(title: "Alert title", message: "Alert message")

好像它们是 viewController 本身的一部分。

Swift SpriteKit: Best practice to access UIViewController in GameScene

注意:正如成员在评论中所说,viewDidLoad 可能很快就会显示警报。尝试使用轻微的延迟或 ViewDidAppear

希望对你有帮助

关于ios - 如何创建可重用的 UIAlertcontroller?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37343355/

相关文章:

ios - 以编程方式将 UIBarButtonItem 设置为 UIBarButtonSystemItem

ios - 我可以以编程方式滚动 WKInterfaceGroup 吗?

ios - 如何根据时间调用2个号码

ios - 将 4 个不同数组的内容按相同顺序排序

iphone - SFHFKeychainUtils "forgot"我的用户密码

iphone - 断言失败

iphone - 在没有 UITableViewController 的情况下使用 NSFetchedResultsController

iphone - App Store 分发配置文件与开发配置文件

swift - 在 Swift 中获取包标识符

swift - 如何快速抛出和处理错误?