swift - 尝试从不同的 Swift 类调用方法

标签 swift xcode uitabbarcontroller

我有两个 swift 类,在一个类中,我需要引用另一个 swift 类中的方法。两个各自的 View Controller 都附加到 tabBarController,所以我尝试创建一个这样的实例:

let mapVC : MapVC = self.tabBarController!.viewControllers![1] as! MapVC
mapVC.loadViewIfNeeded()
mapVC.add(newLocation:location_one) // .add is the method I want to call

MapVC 包含我希望调用的方法。 mapViewtabBar 上的第二个选项,因此索引为 1。但是,我收到错误 [fatal error: unexpectedly found nil while unwrapping an可选值] 当我转换对象 mapVC 时。我认为问题与创建实例 mapVC 有关,我相信我可能没有正确设置它,但我不确定如何修复它。

我不太确定如何表述我的问题,所以如果您仍然感到困惑,我可以在评论中提供更多信息。

最佳答案

我通常使用自定义 tabBarController 作为每个选项卡的委托(delegate)来执行此操作,但我非常喜欢您访问堆栈中的 viewControllers 的方法。让我们找出您的版本有什么问题。

尝试像这样运行它

if let tC = self.tabBarController {
    if let vcs = tC.viewControllers {
        if let map = vcs[1] as? MapVC {
            print("map vc found in stack")
            map.loadViewIfNeeded()
            map.add(newLocation:location_one)
        } else {
            print("no map vc found at index 1")
        }
    } else {
        print("no stack found")
    }
} else {
    print("no tab bar found")
}

这可能有助于我们调试您的代码,您确定返回 nil 的是 mapVC 吗?


编辑:正如您在评论中所描述的,如果您正在远离 tabBarController,那么新出现的 viewController 的 tabBarController 属性将是根据 Apple Docs 为零.

This property is nil if the view controller is not embedded inside a tab bar controller.

一种解决方案是按照此图将 tabBarController 的引用从 vc2 传递到 vc3

[tabBarController]
    |       |
  [vc1]   [vc2]  - both have a reference to tabBarController
            |
          [vc3]  - no reference yet

设置 vc3 来保存 tabBar 引用 - 最好为此创建一个新的 var,而不是使用现有的 tabBarController 属性。

class vc3:UIViewController {

    var tabBarReference:UITabBarController?

    func addALocation(location:CLLocationCoordinate2D) {
        if let tbc = self.tabBarReference {
            if let map = tbc.viewControllers[1] as? MapVC {
                map.loadViewIfNeeded()
                map.add(newLocation:location)
            }
        }
    }

}

然后在 vc2 中使用 prepare for segue 方法访问 vc3 并在它出现之前给它引用。

class vc2:UIViewController {

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let vc3 = segue.destinationViewController as? vc3
            vc3.tabBarReference = self.tabBarController
        }
    }

    func goToVC3() {
        self.performSegueWithIdentifier("goToVC3", sender: nil)
    }

}

我没有测试过这段代码,但理论上它应该可以工作,让我知道你的进展情况。

关于swift - 尝试从不同的 Swift 类调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41770020/

相关文章:

swift - 如何仅将填充添加到 CAShapeLayer 中 UIBezierPath 矩形的外部?

ios - 在 UserDefaults 中保存嵌套字典并管理重复检查 [Swift 4.2]

ios - 代码: "This app could not be installed at this time."

xcode - 如何在 iOS 上调整位图的大小

swift - 点击 TabBar 时更新当前 UIViewController UI

ios - 快速更改为不同选项卡中的 View Controller ?

ios - 声明 `typedef SomeClass<SomeProtocol> MyType` 的 Swift 等价物是什么?

ios - 推送通知在 TestFlight 上不起作用

ios - 错误 ITMS-90207 bundle 无效

iphone - 如何使用新数据重新加载或刷新选项卡栏 Controller 的选项卡栏中的数据?