Support editing a widget only when it appears

This commit is contained in:
david-swift 2024-01-02 08:25:14 +01:00
parent 26b46e3338
commit 350580269f
2 changed files with 13 additions and 4 deletions

View File

@ -11,7 +11,7 @@ import Libadwaita
struct AppearObserver: Widget {
/// The function.
var onAppear: () -> Void
var onAppear: (NativeWidgetPeer) -> Void
/// The content.
var content: View
@ -19,8 +19,9 @@ struct AppearObserver: Widget {
/// - Parameter modifiers: Modify views before being updated.
/// - Returns: The content's container.
func container(modifiers: [(View) -> View]) -> ViewStorage {
onAppear()
return content.storage(modifiers: modifiers)
let storage = content.storage(modifiers: modifiers)
onAppear(storage.view)
return storage
}
/// Update the content.
@ -35,11 +36,18 @@ struct AppearObserver: Widget {
extension View {
/// Run a function on the widget when it appears for the first time.
/// - Parameter closure: The function.
/// - Returns: A view.
public func inspectOnAppear(_ closure: @escaping (NativeWidgetPeer) -> Void) -> View {
AppearObserver(onAppear: closure, content: self)
}
/// Run a function when the view appears for the first time.
/// - Parameter closure: The function.
/// - Returns: A view.
public func onAppear(_ closure: @escaping () -> Void) -> View {
AppearObserver(onAppear: closure, content: self)
inspectOnAppear { _ in closure() }
}
}

View File

@ -38,6 +38,7 @@ This is an overview of the available widgets and other components in _Adwaita_.
| `navigationTitle(_:)` | Add a title that is used if the view is a direct child of a NavigationView. |
| `style(_:)` | Add a style class to the view. |
| `onAppear(_:)` | Run when the view is rendered for the first time. |
| `inspectOnAppear(_:)` | Edit the underlying [Libadwaita][10] class when the view is rendered for the first time.|
| `topToolbar(visible:_:)` | Add a native toolbar to the view. Normally, it contains a HeaderBar. |
| `bottomToolbar(visible:_:)` | Add a native bottom toolbar to the view. |
| `modifyContent(_:modify:)` | Replace all occurrences of a certain view type with another view. |