如何检查我的共享代码是否在 WidgetKit 小部件或完整应用程序中运行?

问题描述 投票:0回答:2

我正在开发一个带有小部件的新 iOS 应用程序。用 SwiftUI 编写。

我的大部分代码在 Widget 目标和 App 目标之间共享,但我想在两个目标之间进行一些小的样式更改。

有没有办法检查代码是在小部件中执行还是在应用程序中执行?

swift swiftui widget ios14 widgetkit
2个回答
6
投票

这里有可能的辅助函数来检测您是否在小部件中运行。使用 Xcode 12 / iOS 14 进行测试。

func isInWidget() -> Bool {
    guard let extesion = Bundle.main.infoDictionary?["NSExtension"] as? [String: String] else { return false }
    guard let widget = extesion["NSExtensionPointIdentifier"] else { return false }
    return widget == "com.apple.widgetkit-extension"
}

0
投票

一种方法是转到小部件目标的

Build Settings
,然后在
Swift Compiler - Custom Flags
Active Compilation Conditions
下添加
WIDGET
等内容到
Alpha
Debug
Release

然后在您的代码中使用:

var title = "app title"
#if WIDGET
    // Do stuff only when compiling the widget
    title = "widget title"
#endif
© www.soinside.com 2019 - 2024. All rights reserved.