From 1e6143accec2c960f01174d53034d55d73561ba1 Mon Sep 17 00:00:00 2001 From: david-swift Date: Wed, 3 Jan 2024 17:17:35 +0100 Subject: [PATCH] Add view modifier detecting clicks on any widget --- Documentation/Reference/extensions/View.md | 6 ++++++ Sources/Adwaita/View/Modifiers/AppearObserver.swift | 7 +++++++ Tests/CarouselDemo.swift | 1 + user-manual/Information/Widgets.md | 1 + 4 files changed, 15 insertions(+) diff --git a/Documentation/Reference/extensions/View.md b/Documentation/Reference/extensions/View.md index ed6466d..8e45b60 100644 --- a/Documentation/Reference/extensions/View.md +++ b/Documentation/Reference/extensions/View.md @@ -36,6 +36,12 @@ Run a function when the view appears for the first time. - Parameter closure: The function. - Returns: A view. +### `onClick(handler:)` + +Run a function when the widget gets clicked. +- Parameter handler: The function. +- Returns: A view. + ### `frame(maxSize:)` Set the view's maximal size. diff --git a/Sources/Adwaita/View/Modifiers/AppearObserver.swift b/Sources/Adwaita/View/Modifiers/AppearObserver.swift index a341e02..e8fbf4b 100644 --- a/Sources/Adwaita/View/Modifiers/AppearObserver.swift +++ b/Sources/Adwaita/View/Modifiers/AppearObserver.swift @@ -50,4 +50,11 @@ extension View { inspectOnAppear { _ in closure() } } + /// Run a function when the widget gets clicked. + /// - Parameter handler: The function. + /// - Returns: A view. + public func onClick(handler: @escaping () -> Void) -> View { + inspectOnAppear { _ = $0.onClick(closure: handler) } + } + } diff --git a/Tests/CarouselDemo.swift b/Tests/CarouselDemo.swift index 79f9512..2e5821a 100644 --- a/Tests/CarouselDemo.swift +++ b/Tests/CarouselDemo.swift @@ -33,6 +33,7 @@ struct CarouselDemo: View { .vexpand() .hexpand() .style("card") + .onClick { print(element.id) } .padding(20) .frame(minWidth: 300, minHeight: 200) .frame(maxSize: 500) diff --git a/user-manual/Information/Widgets.md b/user-manual/Information/Widgets.md index 31bde3e..c1c5b14 100644 --- a/user-manual/Information/Widgets.md +++ b/user-manual/Information/Widgets.md @@ -50,6 +50,7 @@ This is an overview of the available widgets and other components in _Adwaita_. | `toast(_:signal:button:handler:)` | Show a toast with a button on top of the view whenever the signal gets activated. | | `overlay(_:)` | Overlay a view with another view. | | `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. | ### `Button` Modifiers | Syntax | Description |