ios swiftui
WWDC 2020 gave us a lot of enhancements and updates, but the introduction of the WidgetKit framework unarguably stands out.
WWDC 2020给了我们很多增强和更新,但是WidgetKit框架的引入无疑是引人注目的。
iOS 14 has introduced a redesigned home screen, with the inclusion of widgets being a huge addition. Widgets are not just an eye-pleasing UI shortcut for our apps. They also aid in providing useful information to the user from time to time.
iOS 14引入了重新设计的主屏幕,其中包括小部件的增加。 小部件不仅是我们应用程序令人愉悦的UI快捷方式。 它们还有助于不时向用户提供有用的信息。
In some ways, they’re a calmer form of notification that provides you with the latest information from the apps (if the developer has opted to do so) without intruding. Additionally, there’s a new Smart Stack feature in iOS 14 that groups a set of widgets that you can swipe through. Smart Stacks tend to provide the relevant widget at the top by using on-device intelligence that takes into account the time of the day, location, and some other attributes.
在某些方面,它们是一种比较平静的通知形式,可为您提供应用程序的最新信息(如果开发人员选择这样做),而不会造成干扰。 此外,iOS 14中有一个新的智能堆栈功能,该功能将一组可滑动的小部件分组。 智能堆栈倾向于通过使用设备上的智能功能在顶部提供相关的小部件,该功能考虑了一天中的时间,位置和其他一些属性。
WidgetKit is built purely using SwiftUI, which opens endless opportunities for building beautiful widgets. It’s important to note than WidgetKit isn’t meant to build mini-apps.
WidgetKit完全是使用SwiftUI构建的,这为构建漂亮的窗口小部件提供了无限的机会。 值得注意的是,WidgetKit并非旨在构建迷你应用程序。
Besides providing a Link
button that lets you set a deep-link URL to navigate to a particular part of your application, you can’t add any animations or other interactions in widgets.
除了提供允许您设置深层链接URL的Link
按钮以导航到应用程序的特定部分外,您不能在小部件中添加任何动画或其他交互。
我们的目标 (Our Goal)
- Understanding the anatomy of WidgetKit. We’ll explore the framework and see how widgets are created and updated. 了解WidgetKit的结构。 我们将探索该框架,并了解如何创建和更新小部件。
- Build a Joke of the Hour widget in SwiftUI. 在SwiftUI中构建一个小时笑话小部件。
Bundle our SwiftUI application with two widgets by using
WidgetBuilder
.使用
WidgetBuilder
我们的SwiftUI应用程序与两个小部件捆绑WidgetBuilder
。
Without further ado, let’s get started.
事不宜迟,让我们开始吧。
WidgetKit框架:深入了解 (WidgetKit Framework: Under the Hood)
To understand the anatomy of WidgetKit, let’s create a new Xcode 12 SwiftUI project and ensure that the SwiftUI App Lifecycle is chosen.
为了了解WidgetKit的结构,让我们创建一个新的Xcode 12 SwiftUI项目,并确保选择了SwiftUI App Lifecycle。
To create our first widget, Go to File → New → Target and select the Widget Extension template. Make sure you uncheck “Include Configuration Intent,” as we’ll only cover static configurations in this article.
要创建我们的第一个窗口小部件,请转到文件→新建→目标,然后选择窗口小部件扩展模板。 确保取消选中“包括配置意图”,因为本文仅介绍静态配置。