【问题标题】:NativeScript importing iOS framework classes and downcastNativeScript 导入 iOS 框架类并向下转换
【发布时间】:2019-08-19 21:50:15
【问题描述】:

我在 Cocoapod 中有一个自定义的 Swift 框架,封装在一个 NativeScript 插件中。我的 NativeScript TypeScript 代码可以完成访问框架中类中的类和方法所需的一切。要弄清楚所有细微差别,这本身就是一项艰巨的工作。现在我在最后一部分,即从UIViewController 向下转换框架中的自定义viewController。以下代码正在运行,因为 NativeScript 实际加载了我的故事板和控制器:

var podBundle = NSBundle.bundleForClass(CustomViewController)

var bundleUrl = podBundle.URLForResourceWithExtension("MyFramework", "bundle")

var bundle = NSBundle.bundleWithURL(bundleUrl)

var storyboard = UIStoryboard.storyboardWithNameBundle("Main", bundle)

var viewController = storyboard.instantiateViewControllerWithIdentifier("CustomViewControllerID")

console.log(viewController)
console.log(viewController instanceof CustomViewController)

application.ios.rootController.presentViewControllerAnimatedCompletion(viewController, true, null)

第一个console.log实际上记录了整个类,如MyFramework.CustomViewController: hexcodehere

第二个console.log 也记录为true,这意味着它知道viewController 变量的类型确实是CustomViewController

问题是,我需要调用CustomViewController中的一个函数,所以我需要向下转型:

storyboard.instantiateViewControllerWithIdentifier("CustomViewControllerID") as CustomViewController

但是编译器对CustomViewController 说“找不到名称”。如果我尝试MyFramework.CustomViewController,它会向 MyFramework 显示“找不到名称”。通知NSBundle.bundleForClass(CustomViewController) 有效。这意味着编译器知道 CustomViewController。

如果我在文件顶部导入插件:

import { CustomViewController } from "myplugin",它对 myplugin 说“找不到模块”。请注意,我实际上可以访问此插件中的所有类。所以插件肯定是正确安装的。它是从本地文件路径安装的,而不是 git。

似乎我错过了一些非常简单的东西。但我一辈子都想不通。

我很乐意帮助其他想要使用原生 iOS 故事板和 Swift 类等的人。

【问题讨论】:

  • storyboard.instantiateViewControllerWithIdentifier("CustomViewControllerID") 已经返回正确的控制器了吗?
  • 是的。然后使用该控制器的 presentView 加载具有所有正确交互的正确视图和控制器。这就是为什么它如此令人沮丧。

标签: nativescript


【解决方案1】:

证明了大脑在后台处理问题的能力,我突然想到了它。由于运行时知道类型,我所要做的就是强制转换为“any”来解决编译器问题:

var viewController = storyboard.instantiateViewControllerWithIdentifier("CustomViewControllerID") as any

然后编译器允许我调用我的 CustomViewController viewcontroller 实例上的任何函数而无需抱怨,并且运行时也很好。为了更加安全,将对子类方法的调用包装在 if instanceof 块中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多