【问题标题】:Swift - Call AviewController method from BviewControllerSwift - 从 BviewController 调用 AviewController 方法
【发布时间】:2015-10-15 23:59:41
【问题描述】:

我有两个 viewControllers (AviewController & BviewController) 没有使用 segue 连接。 在 AviewController 我有一个 UIScrollview。

我要做的是从 BviewController 调用一个函数,该函数将禁用 AviewController 中的滚动视图( AviewController.scrollView.scrollEnabled = false )

如果不使用 segue,我怎么能做到这一点?

BviewController:

var AV = AviewController ()

func disable_AscrollView (){
         AviewController.scrollView.scrollEnabled = false 
}

【问题讨论】:

    标签: ios xcode swift methods uiviewcontroller


    【解决方案1】:

    好吧,您描述的代码不起作用,因为AV 与屏幕上显示的AviewController 实例不同。

    有几种选择可以获取正确的实例,这取决于哪种情况最好。

    1. 如果您确定整个应用程序中只有一个AviewController,您可以声明一个static var sharedInstance: AviewController,并在viewDidLoad 函数中将此变量设置为self。现在,从您应用中的任何地方,您可以将其称为AviewController.sharedInstance 并调用其函数,例如一个自定义的disableScrollView 函数。(这似乎不适用于 Swift,请参阅 cmets。)

    2. 如果AviewController 在视图层次结构中有固定位置,您可以通过应用程序委托的window 属性找到它,例如

      UIApplication.sharedApplication().delegate.window.rootViewController
      

      根视图控制器可能是UINavigationController,在这种情况下您必须深入挖掘。

    3. 使用NSNotificationCenter。在AviewControllerviewDidLoad 中注册通知:

      NSNotificationCenter.defaultCenter().addObserver(self,
          selector: "disableScrollView:",
          name: "DisableScrollView",
          object: nil)
      

      实现disableScrollView 函数(使用@objc 将其用作选择器):

      @objc func disableScrollView(notification: NSNotification) {
          // do something
      }
      

      当需要禁用滚动视图时,您可以调用

      NSNotificationCenter.defaultCenter().postNotificationName(
          "DisableScrollView", object: nil)
      

      来自BviewController

    【讨论】:

    • 感谢 Glorfindel,AviewController 是应用程序中唯一的一个,但是,如果我使用 static var sharedInstance: ViewController 我会收到错误消息:class var declaration requires an initialiser....
    • 您能否将nil 设置为静态变量的初始值?
    • 添加'static var sharedInstance: ViewController = nil'给我一个错误:不符合协议'NilLiteralConvertible'
    • OK - 那么使用 Swift 实现这一点比我想象的要难。那么,也许使用NSNotificationCenter 是一个更简单的选择。
    • 我在查看 NSNotificationCenter 但是找不到如何在 viewControillers 之间发送它
    【解决方案2】:

    如果你的 AViewController 只是 init,你可以在 init 和 push/present 方法之间修改它的属性。

    如果 AViewController 已经推送/呈现但不在视图控制器层的顶部(如在 AViewController 中推送 BViewController),您可以尝试委托或通知。

    设置BViewController的delegate为AViewController,可以在AViewController实现的BViewController中使用self.delegate?.disableScrollInAViewController()

    或者只是在 AViewController 中注册一个通知,然后在 BViewController 中发布通知。

    【讨论】:

    • 如何在swift中注册通知?
    • @SNos 使用NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodYouWantToPerform:", name: "yourNotificationName", object: nil)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多