Swift 5.3 为提供的资源增加了对 SPM 的改进,因此完成您所要求的一种方法是让您的 swift 包出售图像,然后通过支持 Storyboard 视图的UIViewController 加载这些图像。
可以在here 找到 Apple 的捆绑资源文档。
以下是重点:
确保您的 swift 包具有为目标声明的资源:
targets: [
.target(
name: "MyLibrary",
resources: [
.process("Resources")
// This will process the /Sources/MyLibrary/Resources directory.
]
),
]
当资源被声明时,一个新的Bundle 引用变为可用,它引用了包资源。 Bundle.module 引用可用于加载和提供图像。在您的 swift 包中,您可以指定可用的图像,例如:
#if canImport(UIKit)
import UIKit
public extension UIImage {
static var myImage: UIImage? = UIImage(named: "ImageName", bundle: Bundle.module, compatibleWith: nil)
}
#endif
现在,在您的UIViewController 中,您应该可以导入您的包,并将图像分配给@IBOutlet:
import UIKit
import MyLibrary
class ViewController: UIViewController {
@IBOutlet var imageView: UIImageView!
func viewDidLoad() {
super.viewDidLoad
imageView.image = .myImage
}
}
另一种方法是通过您的库提供自定义UIImageView 类,该类将从Bundle.module 加载图像。这可以通过 Storyboard 来实现,但您将失去在原地查看图像的能力。例如,如果我在我的 swift 包中声明了这个类:
public class AppIconImageView: UIImageView {
@IBInspectable var imageName: String = "" {
didSet {
image = UIImage(named: imageName, in: Bundle.module, compatibleWith: nil)
}
}
}
然后我可以在 Storyboard 中使用该类。通过imageName 运行时属性提供要显示的图像的名称。 (然后您可以在 Interface Builder 中取消设置“图像”设置。)
就像我提到的,图像不会显示在故事板中(@IBDesignable 在其他模块中通常很棘手),但在运行时,包资源应该加载。