18

I'm exploring tvOS and I found that Apple offers nice set of templates written using TVML. I'd like to know if a tvOS app that utilises TVML templates can also use UIKit.

Can I mix UIKit and TVMLKit within one app?

I found a thread on Apple Developer Forum but it does not fully answer this question and I am going through documentation to find an answer.

4

4 回答 4

33

是的你可以。显示 TVML 模板需要您使用控制 JavaScript 上下文的对象:TVApplicationController

var appController: TVApplicationController?

这个对象有一个与之关联的UINavigationController属性。因此,只要您认为合适,您就可以致电:

let myViewController = UIViewController()
self.appController?.navigationController.pushViewController(myViewController, animated: true)

这允许您将自定义 UIKit 视图控制器推送到导航堆栈上。如果您想返回 TVML 模板,只需将 viewController 从导航堆栈中弹出即可。

如果您想知道如何在 JavaScript 和 Swift 之间进行通信,这里有一个方法可以创建一个名为pushMyView()的 javascript 函数

func createPushMyView(){

    //allows us to access the javascript context
    appController?.evaluateInJavaScriptContext({(evaluation: JSContext) -> Void in

        //this is the block that will be called when javascript calls pushMyView()
        let pushMyViewBlock : @convention(block) () -> Void = {
            () -> Void in

            //pushes a UIKit view controller onto the navigation stack
            let myViewController = UIViewController()
            self.appController?.navigationController.pushViewController(myViewController, animated: true)
        }

        //this creates a function in the javascript context called "pushMyView". 
        //calling pushMyView() in javascript will call the block we created above.
        evaluation.setObject(unsafeBitCast(pushMyViewBlock, AnyObject.self), forKeyedSubscript: "pushMyView")
        }, completion: {(Bool) -> Void in
        //done running the script
    })
}

一旦你在 Swift 中调用 createPushMyView(),你就可以在你的 javascript 代码中调用pushMyView(),它会将视图控制器推送到堆栈上。

斯威夫特 4.1 更新

只需对方法名称和转换进行一些简单的更改:

appController?.evaluate(inJavaScriptContext: {(evaluation: JSContext) -> Void in

evaluation.setObject(unsafeBitCast(pushMyViewBlock, to: AnyObject.self), forKeyedSubscript: "pushMyView" as NSString)
于 2015-11-04T20:31:39.553 回答
6

正如接受的答案中提到的,您可以从 JavaScript 上下文中调用几乎任何 Swift 函数。请注意,顾名思义,setObject:forKeyedSubscript:除了块之外,它还将接受对象(如果它们符合从 JSExport 继承的协议),允许您访问该对象上的方法和属性。这是一个例子

import Foundation
import TVMLKit

// Just an example, use sessionStorage/localStorage JS object to actually accomplish something like this
@objc protocol JSBridgeProtocol : JSExport {
    func setValue(value: AnyObject?, forKey key: String)
    func valueForKey(key: String) -> AnyObject?
}

class JSBridge: NSObject, JSBridgeProtocol {
    var storage: Dictionary<String, String> = [:]
    override func setValue(value: AnyObject?, forKey key: String) {
        storage[key] = String(value)
    }
    override func valueForKey(key: String) -> AnyObject? {
        return storage[key]
    }
}

然后在您的应用控制器中:

func appController(appController: TVApplicationController, evaluateAppJavaScriptInContext jsContext: JSContext) {
    let bridge:JSBridge = JSBridge();
    jsContext.setObject(bridge, forKeyedSubscript:"bridge");
}

然后你可以在你的 JS 中这样做:bridge.setValue(['foo', 'bar'], "baz")

不仅如此,您还可以覆盖现有元素的视图,或定义要在标记中使用的自定义元素,并使用本机视图支持它们:

// Call lines like these before you instantiate your TVApplicationController 
TVInterfaceFactory.sharedInterfaceFactory().extendedInterfaceCreator = CustomInterfaceFactory() 
// optionally register a custom element. You could use this in your markup as <loadingIndicator></loadingIndicator> or <loadingIndicator /> with optional attributes. LoadingIndicatorElement needs to be a TVViewElement subclass, and there are three functions you can optionally override to trigger JS events or DOM updates
TVElementFactory.registerViewElementClass(LoadingIndicatorElement.self, forElementName: "loadingIndicator")

快速自定义元素示例:

import Foundation
import TVMLKit

class LoadingIndicatorElement: TVViewElement {
    override var elementName: String {
        return "loadingIndicator"
    }

    internal override func resetProperty(resettableProperty: TVElementResettableProperty) {
        super.resetProperty(resettableProperty)
    }
    // API's to dispatch events to JavaScript
    internal override func dispatchEventOfType(type: TVElementEventType, canBubble: Bool, cancellable isCancellable: Bool, extraInfo: [String : AnyObject]?, completion: ((Bool, Bool) -> Void)?) {
        //super.dispatchEventOfType(type, canBubble: canBubble, cancellable: isCancellable, extraInfo: extraInfo, completion: completion)
    }

    internal override func dispatchEventWithName(eventName: String, canBubble: Bool, cancellable isCancellable: Bool, extraInfo: [String : AnyObject]?, completion: ((Bool, Bool) -> Void)?) {
        //...
    }
}

以下是设置自定义接口工厂的方法:

class CustomInterfaceFactory: TVInterfaceFactory {
    let kCustomViewTag = 97142 // unlikely to collide
    override func viewForElement(element: TVViewElement, existingView: UIView?) -> UIView? {

        if (element.elementName == "title") {
            if (existingView != nil) {
                return existingView
            }

            let textElement = (element as! TVTextElement)
            if (textElement.attributedText!.length > 0) {
                let label = UILabel()                    

                // Configure your label here (this is a good way to set a custom font, for example)...  
                // You can examine textElement.style or textElement.textStyle to get the element's style properties
                label.backgroundColor = UIColor.redColor()
                let existingText = NSMutableAttributedString(attributedString: textElement.attributedText!)
                label.text = existingText.string
                return label
            }
        } else if element.elementName == "loadingIndicator" {

            if (existingView != nil && existingView!.tag == kCustomViewTag) {
                return existingView
            }
            let view = UIImageView(image: UIImage(named: "loading.png"))
            return view // Simple example. You could easily use your own UIView subclass
        }

        return nil // Don't call super, return nil when you don't want to override anything... 
    }

    // Use either this or viewForElement for a given element, not both
    override func viewControllerForElement(element: TVViewElement, existingViewController: UIViewController?) -> UIViewController? {
        if (element.elementName == "whatever") {
            let whateverStoryboard = UIStoryboard(name: "Whatever", bundle: nil)
            let viewController = whateverStoryboard.instantiateInitialViewController()
            return viewController
        }
        return nil
    }


    // Use this to return a valid asset URL for resource:// links for badge/img src (not necessary if the referenced file is included in your bundle)
    // I believe you could use this to cache online resources (by replacing resource:// with http(s):// if a corresponding file doesn't exist (then starting an async download/save of the resource before returning the modified URL). Just return a file url for the version on disk if you've already cached it.
    override func URLForResource(resourceName: String) -> NSURL? {
        return nil
    }
}

不幸的是,不会为所有元素调用 view/viewControllerForElement:。一些现有的元素(如集合视图)将自己处理其子元素的呈现,而不涉及您的界面工厂,这意味着您必须覆盖更高级别的元素,或者可能使用类别/swizzling 或 UIAppearance 来获取你想要的效果。

最后,正如我刚才所暗示的,您可以使用 UIAppearance 来更改某些内置视图的外观。这是更改 TVML 应用程序标签栏外观的最简单方法,例如:

 // in didFinishLaunching...
 UITabBar.appearance().backgroundImage = UIImage()
 UITabBar.appearance().backgroundColor = UIColor(white: 0.5, alpha: 1.0)
于 2016-03-05T11:17:45.710 回答
5

如果你已经有一个适用于 tvOS 的原生 UIKit 应用程序,但想通过使用 TVMLKit 来扩展它,你可以。

将 TVMLKit 用作原生 tvOS 应用程序中的子应用程序。下面的应用程序展示了如何做到这一点,通过保留TVApplicationController和呈现navigationController来自TVApplicationController. TVApplicationControllerContext用于将数据传输到 JavaScript 应用程序,因为 url 在此处传输:

class ViewController: UIViewController, TVApplicationControllerDelegate {
    // Retain the applicationController
    var appController:TVApplicationController?
    static let tvBaseURL = "http://localhost:9001/"
    static let tvBootURL = "\(ViewController.tvBaseURL)/application.js"

    @IBAction func buttonPressed(_ sender: UIButton) {
        print("button")

        // Use TVMLKit to handle interface

        // Get the JS context and send it the url to use in the JS app
        let hostedContContext = TVApplicationControllerContext()
        if let url = URL(string:  ViewController.tvBootURL) {
            hostedContContext.javaScriptApplicationURL = url
        }

        // Save an instance to a new Sub application, the controller already knows what window we are running so pass nil
        appController = TVApplicationController(context: hostedContContext, window: nil, delegate: self)

        // Get the navigationController of the Sub App and present it
        let navc = appController!.navigationController
        present(navc, animated: true, completion: nil)
    }
于 2016-12-11T21:24:35.490 回答
-2

是的。请参阅TVMLKit 框架,其文档以:

TVMLKit 框架使您能够将 JavaScript 和 TVML 文件合并到二进制应用程序中以创建客户端-服务器应用程序。

从这些文档的快速浏览来看,您似乎使用各种TVWhateverFactory类从 TVML 创建 UIKit 视图或视图控制器,之后您可以将它们插入到 UIKit 应用程序中。

于 2015-10-24T16:48:36.380 回答