Swift - 从 BviewController 调用 AviewController 方法

Swift - Call AviewController method from BviewController

我有两个 viewController(AviewController 和 BviewController)在没有使用 segue 的情况下连接。 在 AviewController 中我有一个 UIScrollview。

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

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

BviewController:

var AV = AviewController ()

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

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

获取正确实例有多种选择,视情况而定。

  1. 如果你确定你的整个应用中只有一个AviewController,你可以声明一个static var sharedInstance: AviewController,并将这个变量设置为selfviewDidLoad 函数中。现在,从您应用中的 处处 ,您可以将其称为 AviewController.sharedInstance 并调用其函数,例如自定义 disableScrollView 函数。(这似乎不适用于 Swift,请参阅评论。)

  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.

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

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

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

或者只在 AViewController 中注册通知,post在 BViewController 中注册通知。