【问题标题】:Calling presentViewController from custom class从自定义类调用 presentViewController
【发布时间】:2015-05-10 19:55:46
【问题描述】:

我阅读了this postthis one,了解如何在 UIViewController 子类之外调用 presentViewController 表单。在我的例子中,自定义类是 NSObject 的子类。以下方法是唯一有效的方法(来自我阅读的示例):

UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)

我的问题:有没有更好的不依赖 appDelegate 的解决方案(据我了解,这种方法在设计方面不是很整洁)...

【问题讨论】:

    标签: ios swift uialertcontroller


    【解决方案1】:

    我有时会创建一个实用程序类来显示警报等。我通常做的是让我呈现视图控制器的方法将当前视图控制器作为参数。这种方法效果很好。

    编辑:

    这是我的一个项目中文件 Utils.swift 中的一个示例方法。它定义了一个在当前视图控制器上显示 UIAlertController 警报的类函数:

    class Utils
    {
      static let sharedUtils = Utils()
      
      class func showAlertOnVC(
        targetVC: UIViewController, 
        var title: String, 
        var message: String)
      {
        title = NSLocalizedString(title, comment: "")
        message = NSLocalizedString(message, comment: "")
        let alert = UIAlertController(
          title: title, 
          message: message, 
          preferredStyle: UIAlertControllerStyle.Alert)
        let okButton = UIAlertAction(
          title:"OK",
          style: UIAlertActionStyle.Default,
          handler:
          {
            (alert: UIAlertAction!)  in
        })
        alert.addAction(okButton)
        targetVC.presentViewController(alert, animated: true, completion: nil)
      }
    }
    

    上面的代码定义了一个类 Utils。请注意,它没有任何基类,这在 Swift 中是可以的。

    接下来,它定义了一个公共静态变量 sharedUtils,您可以使用它来访问单例 Utils 类。

    最后,它定义了一个类方法showAlertOnVC,可用于在当前视图控制器之上显示一个 UIAlertController 警报。要使用showAlertOnVC,您可以从当前视图控制器调用它并将self 作为targetVC 参数传递。

    【讨论】:

    • 实用程序类的子类是什么类?
    • 没关系。在 Objective-C 中,NSObject.在 Swift 中,没有基类。
    • 但这与我当前的解决方案相当,它也没有基类。我的问题是如何避免调用 AppDelegate,如果这个类没有子类化 ViewController,我想这仍然是必要的......
    • 没有。创建一个实用程序类。把你的方法放进去。如果方法需要实例变量,您可以将它们设为类方法,或者您可以将实用程序类设为单例。与 Objective-C 不同,Swift 中的类不必继承任何东西。
    • 这似乎有效!为清楚起见,您可以考虑将代码格式化为代码。不过,我接受了你的回答……谢谢!
    【解决方案2】:

    我认为这是最简单的解决方案:

    class Utils {
      static  func displayTheAlert(targetVC: UIViewController, title: String, message: String){
            let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction((UIAlertAction(title: "OK", style: .Default, handler: {(action) -> Void in
            })))
            targetVC.presentViewController(alert, animated: true, completion: nil)
        }
    }
    

    //然后调用它

    Utils.displayTheAlert(self, title: "Fout", message: "Uw bestelling is nog niet klaar")
    

    【讨论】:

      【解决方案3】:

      从View的设计角度来看,模型类(NSObject)直接与View交互是不可取的。它不符合 MVC 模式。避免在 NSObject 类中使用 UIKIT。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-01
        相关资源
        最近更新 更多