我正在开发一个带有小部件的新 iOS 应用程序。用 SwiftUI 编写。
我的大部分代码在 Widget 目标和 App 目标之间共享,但我想在两个目标之间进行一些小的样式更改。
有没有办法检查代码是在小部件中执行还是在应用程序中执行?
这里有可能的辅助函数来检测您是否在小部件中运行。使用 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"
}
一种方法是转到小部件目标的
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