首页 > 解决方案 > 将主故事板存储在 Swift 包中

问题描述

我在 Xcode 中使用 Swift Packages。我想知道是否可以将您的应用程序的“主故事板”移动到 Swift 包中。“主情节提要”是指在您info.plist的键下设置的那个NSMainStoryboardFile(人类可读的名称是Main storyboard file base name (macOS)

这是我的包的文件夹结构:

.
├── Package.swift
├── README.md
├── Sources
│   └── FooPackage
│       ├── FooPackage.swift
│       └── Resources
│           ├── Base.lproj
│           │   └── Main\ Menu.storyboard
│           └── img.png
└── Tests
    └── FooPackageTests
        └── FooPackageTests.swift

这是我的package.swift文件,与 Xcode 模板相同:

// swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.

// swift-tools-version:5.3

import PackageDescription

let package = Package(
    name: "FooPackage",
    defaultLocalization: "en",
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "FooPackage",
            targets: ["FooPackage"]),
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        // .package(url: /* package url */, from: "1.0.0"),
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages this package depends on.
        .target(
            name: "FooPackage",
            dependencies: []),
        .testTarget(
            name: "FooPackage",
            dependencies: ["FooPackage"]),
    ]
)

在单元测试中,我检查我的故事板是否可以访问,它是:

print(Bundle.module.path(forResource: "Main Menu", ofType: "storyboard")!)
// => /Users/Alex/FooPackage/.build/x86_64-apple-macosx/debug/FooPackage_FooPackage.bundle/Base.lproj/Main Menu.storyboard

如您所见,我通过Bundle.module. 包含此 Swift 包的其他应用程序将无法访问该访问器。据我所知,这是一个预期的设计:您的包应该使用明确定义的公共 API 公开其“共享”捆绑资源。

info.plist尽管如此,这似乎与主故事板驻留在主包中的期望不兼容。有没有解决的办法?

标签: swiftxcodemacosappkitswift-package-manager

解决方案


我以前处理过这个,我记不清了,但我认为你需要在 package 中的依赖项之后添加这个

        resources: [
            .process("Main Menu")
        ]),

请记住,它不会是默认的故事板。您必须从代码中调用它。


推荐阅读