Update documentation for creating widgets

This commit is contained in:
david-swift 2023-11-26 15:28:08 +01:00
parent 7a97d36585
commit 8452031adb

View File

@ -25,29 +25,29 @@ struct CustomText: Widget {
var text: String var text: String
public func container() -> ViewStorage { } public func container(modifiers: [(View) -> View]) -> ViewStorage { }
public func update(_ storage: ViewStorage) { } public func update(_ storage: ViewStorage, modifiers: [(View) -> View]) { }
} }
``` ```
## The `container()` Function ## The `container(modifiers:)` Function
This function initializes the widget when the widget appears for the first time. This function initializes the widget when the widget appears for the first time.
It expects a `ViewStorage` as the return type. It expects a `ViewStorage` as the return type.
In our case, this function is very simple: In our case, this function is very simple:
```swift ```swift
func container() -> ViewStorage { func container(modifiers: [(View) -> View]) -> ViewStorage {
.init(MarkupLabel(self.text)) .init(MarkupLabel(self.text))
} }
``` ```
`MarkupLabel` is defined in [Libadwaita][1]. `MarkupLabel` is defined in [Libadwaita][1].
## The `update(_:)` Function ## The `update(_:modifiers:)` Function
Whenever a state of the app changes, the `update(_:)` function of the widget gets called. Whenever a state of the app changes, the `update(_:)` function of the widget gets called.
You get the view storage that you have previously initialized as a parameter. You get the view storage that you have previously initialized as a parameter.
Update the storage to reflect the current state of the widget: Update the storage to reflect the current state of the widget:
```swift ```swift
func update(_ storage: ViewStorage) { func update(_ storage: ViewStorage, modifiers: [(View) -> View]) {
if let label = storage.view as? MarkupLabel { if let label = storage.view as? MarkupLabel {
label.setText(text) label.setText(text)
} }
@ -57,7 +57,7 @@ func update(_ storage: ViewStorage) {
## Containers ## Containers
Some widgets act as containers that accept other widgets as children. Some widgets act as containers that accept other widgets as children.
In that case, use the `ViewStorage`'s `content` property for storing their view storages. In that case, use the `ViewStorage`'s `content` property for storing their view storages.
In the `update(_:)` function, update the children's storages. In the `update(_:modifiers:)` function, update the children's storages.
An example showcasing how to implement containers is the [VStack][2]. An example showcasing how to implement containers is the [VStack][2].
[1]: https://github.com/AparokshaUI/Libadwaita [1]: https://github.com/AparokshaUI/Libadwaita