Add view modifier to observe and set focus

This commit is contained in:
david-swift 2024-02-14 18:25:12 +01:00
parent ffdb727a00
commit 9e05b2692b
3 changed files with 24 additions and 0 deletions

View File

@ -159,6 +159,12 @@ Set the view's visibility.
- Parameter visible: Whether the view is visible. - Parameter visible: Whether the view is visible.
- Returns: A view. - Returns: A view.
### `focused(_:)`
Bind to the view's focus.
- Parameter focus: Whether the view is focused.
- Returns: A view.
### `stopModifiers()` ### `stopModifiers()`
Remove all of the content modifiers for the wrapped views. Remove all of the content modifiers for the wrapped views.

View File

@ -138,4 +138,21 @@ extension View {
inspect { gtk_widget_set_visible($0.pointer?.cast(), visible.cBool) } inspect { gtk_widget_set_visible($0.pointer?.cast(), visible.cBool) }
} }
/// Bind to the view's focus.
/// - Parameter focus: Whether the view is focused.
/// - Returns: A view.
public func focused(_ focused: Binding<Bool>) -> View {
inspect { storage in
storage.notify(name: "has-focus", id: "focused") {
let newValue = gtk_widget_has_focus(storage.pointer?.cast()) != 0
if focused.wrappedValue != newValue {
focused.wrappedValue = newValue
}
}
if focused.wrappedValue != (gtk_widget_has_focus(storage.pointer?.cast()) != 0) {
gtk_widget_grab_focus(storage.pointer?.cast())
}
}
}
} }

View File

@ -47,6 +47,7 @@ There are many more widgets available using auto-generation. Learn [how to use t
| `overlay(_:)` | Overlay a view with another view. | | `overlay(_:)` | Overlay a view with another view. |
| `insensitive(_:)` | Make a view unable to detect actions. This is especially useful for overlays. | | `insensitive(_:)` | Make a view unable to detect actions. This is especially useful for overlays. |
| `onClick(handler:)` | Run a function when the user clicks on the widget. | | `onClick(handler:)` | Run a function when the user clicks on the widget. |
| `focused(_:)` | Set and observe whether a view is focused. |
| `verticalCenter()` | Wrap a view in a `VStack` and center vertically. | | `verticalCenter()` | Wrap a view in a `VStack` and center vertically. |
| `horizontalCenter()` | Wrap a view in an `HStack` and center horizontally. | | `horizontalCenter()` | Wrap a view in an `HStack` and center horizontally. |