From 1e9aa876dbe77b303c6cd5fc8024da5b9a0d1de3 Mon Sep 17 00:00:00 2001 From: Matt Bruce Date: Thu, 8 Aug 2024 10:59:30 -0500 Subject: [PATCH] refactor for use in both UIControl and UIView Signed-off-by: Matt Bruce --- VDS/Protocols/Clickable.swift | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/VDS/Protocols/Clickable.swift b/VDS/Protocols/Clickable.swift index c2fc9056..fe6ff10d 100644 --- a/VDS/Protocols/Clickable.swift +++ b/VDS/Protocols/Clickable.swift @@ -9,12 +9,12 @@ import Foundation import UIKit import Combine -public protocol Clickable: ViewProtocol where Self: UIControl { +public protocol Clickable: ViewProtocol { /// Sets the primary Subscriber used for the UIControl event .touchUpInside. var onClickSubscriber: AnyCancellable? { get set } } -extension Clickable { +extension Clickable where Self: UIControl { /// Allows the setting of a completion block against the onClickSubscriber cancellable. This will /// completion block will get executed against the UIControl publisher for the 'touchUpInside' action. public var onClick: ((Self) -> ())? { @@ -23,7 +23,7 @@ extension Clickable { onClickSubscriber?.cancel() if let newValue { onClickSubscriber = publisher(for: .touchUpInside) - .sink { [weak self] c in + .sink { [weak self] c in guard let self, self.isEnabled else { return } newValue(c) } @@ -34,3 +34,24 @@ extension Clickable { } } } + +extension Clickable where Self: UIView { + /// Allows the setting of a completion block against the onClickSubscriber cancellable. This will + /// completion block will get executed against the UIControl publisher for the 'touchUpInside' action. + public var onClick: ((Self) -> ())? { + get { return nil } + set { + onClickSubscriber?.cancel() + if let newValue { + onClickSubscriber = publisher(for: UITapGestureRecognizer()) + .sink { [weak self] _ in + guard let self, self.isEnabled else { return } + newValue(self) + } + } else { + onClickSubscriber = nil + } + setNeedsUpdate() + } + } +}