From af43eb9da7df7ba5fbb9c9e16dd57e7db9ad2099 Mon Sep 17 00:00:00 2001 From: Vlad Date: Wed, 26 Aug 2020 23:40:46 +0300 Subject: [PATCH] Add Refresh Control --- TIUIElements/README.md | 4 +- .../Views/RefreshControl/RefreshControl.swift | 45 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 TIUIElements/Sources/Views/RefreshControl/RefreshControl.swift diff --git a/TIUIElements/README.md b/TIUIElements/README.md index 50d4e5af..a24f58bf 100644 --- a/TIUIElements/README.md +++ b/TIUIElements/README.md @@ -1,6 +1,8 @@ # TIUIElements -Bunch of useful protocols and views. +Bunch of useful protocols and views: + +- RefreshControl - a basic UIRefreshControl with fixed refresh action. # Installation via SPM diff --git a/TIUIElements/Sources/Views/RefreshControl/RefreshControl.swift b/TIUIElements/Sources/Views/RefreshControl/RefreshControl.swift new file mode 100644 index 00000000..452fd057 --- /dev/null +++ b/TIUIElements/Sources/Views/RefreshControl/RefreshControl.swift @@ -0,0 +1,45 @@ +import UIKit + +open class RefreshControl: UIRefreshControl { + private var action: Selector? + private var target: NSObjectProtocol? + + public override func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControl.Event) { + guard case .valueChanged = controlEvents else { + return super.addTarget(target, action: action, for: controlEvents) + } + + self.action = action + self.target = target as? NSObjectProtocol + } + + public override func removeTarget(_ target: Any?, action: Selector?, for controlEvents: UIControl.Event) { + guard self.action == action, self.target?.isEqual(target) ?? false else { + super.removeTarget(target, action: action, for: controlEvents) + return + } + + self.action = nil + self.target = nil + } + + public override func sendActions(for controlEvents: UIControl.Event) { + guard case .valueChanged = controlEvents else { + return super.sendActions(for: controlEvents) + } + + if action != nil, target != nil { + performRefreshAction() + } + } + + private func performRefreshAction() { + CFRunLoopPerformBlock(CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue) { [weak self] in + guard let action = self?.action else { + return + } + + self?.target?.perform(action) + } + } +}