Как создать многоразовый 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)
    }
}

и я называю это в моем другом контроллере представления, как

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

3 ответа

Решение

Представить свое предупреждение в main_queue

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

        dispatch_async(dispatch_get_main_queue(), {
            view.presentViewController(alert, animated: true, completion: nil)
        })
    }
}

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 для отображения предупреждений.

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

Теперь в ваших viewControllers, где вам нужно показывать оповещения, вы просто соответствуете протоколу

class ViewController: UIViewController, Alertable { } 

и вызвать методы как

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

как будто они являются частью самого viewController.

Swift SpriteKit: лучшая практика для доступа к UIViewController в GameScene

Примечание. Как отмечают участники в комментариях, viewDidLoad может вскоре показать предупреждение. Попробуйте использовать небольшую задержку или ViewDidAppear

Надеюсь это поможет

ПРИМЕНИМОЕ ПРЕДУПРЕЖДЕНИЕ в быстрых 3 и 4

class AlertView: NSObject {
    class func showAlert(view: UIViewController , title: String , message: String){
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
        view.present(alert, animated: true, completion: nil)
    }
}

 //How to use?
 //Alert.showAlert(view: self, title: "Alert!", message: "Reusable Alert")
Другие вопросы по тегам