在Swift框架中加载资源(例如storyboard) [英] Loading a resource (e.g. storyboard) in a Swift framework

查看:446
本文介绍了在Swift框架中加载资源(例如storyboard)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个捆绑故事板的框架。我已经检查过,创建的.framework包含我的.storyboard文件(作为 .storyboardc 文件),并且已经获得了在运行时加载storyboard的框架。然而,这是一个框架,我希望代码尽可能多样化,我觉得我目前的解决方案有点hacky。目前,我正在使用以下代码加载故事板:

I'm trying to make a framework that will bundle a storyboard. I have checked, and the created .framework includes my .storyboard file (as a .storyboardc file), and have gotten the framework to load the storyboard at runtime. However, this being a framework, I'd like for the code to be as versatile as possible, and I feel like my current solution is a little hacky. Currently, I'm loading the storyboard using the following code:

let mainBundlePath: String = NSBundle.mainBundle().resourcePath
let frameworkBundlePath = mainBundlePath.stringByAppendingPathComponent("Frameworks/AuthenticationManager.framework")
let frameworkBundle = NSBundle(path: frameworkBundlePath)
let storyboard = UIStoryboard(name: "Storyboard", bundle: frameworkBundle)

我注意到的一些事情可能有些问题:

A couple of things I've noticed that could be gotchas:


  • 框架的路径( Frameworks / )可能在将来发生变化,不应依赖于?

  • 框架的名称可能会改变,但如果没有先得到框架的 NSBundle ,就无法获得产品名称?

  • 框架不是真正的捆绑包(?),所以将它们作为捆绑包加载可能会在将来产生无法预料的后果吗?

  • The path of the framework (Frameworks/) could, potentially, change in the future, and should not relied upon?
  • The name of the framework could change, but without first getting the NSBundle of the framework there's no way of getting the product name?
  • Frameworks aren't really bundles (?), so loading them as a bundle could have unforeseen consequences in the future?

可能是其他问题,上述问题的解决方案,或上述问题可能不是问题,但我无法想到它们。

There may be other issues, solutions to the above issues, or the above issues may not be issues after all, but I've not been able to think of them.

这个问题可能更适合代码审查,但我觉得它也适合这里。如果它需要移动到那里,请随意这样做或告诉我这样做。

This question may be be more suited for Code Review, but I felt it'd fit in well here, too. If it needs to be moved over there, feel free to do that or tell me to do it.

推荐答案

这是一个更清洁的解决方案(不涉及框架标识符):

Here's a cleaner solution (no framework identifiers involved):

let storyboardName = "StoryboardName"
let storyboardBundle = NSBundle(forClass: self)
let storyboard = UIStoryboard(name: storyboardName, bundle: storyboardBundle)

如果此代码是不在静态方法内,使用 YourClass.self 而不是 self

If this code is not inside of a static method, use YourClass.self instead of self.

Swift 3示例:

let storyboardBundle = Bundle(for: NumberPadViewController.self)
super.init(nibName: "NumberPadViewController", bundle: storyboardBundle)

这篇关于在Swift框架中加载资源(例如storyboard)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆