Last active
July 17, 2018 11:10
-
-
Save AshvinGudaliya/2e0865b108c2360bcaf12da404d54ee8 to your computer and use it in GitHub Desktop.
PullToRefresh using UIRefreshControl directly property type.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
extension UITableView { | |
private struct AssociatedKeys { | |
static var ActionKey = "UIRefreshControlActionKey" | |
} | |
private class ActionWrapper { | |
let action: RefreshControlAction | |
init(action: @escaping RefreshControlAction) { | |
self.action = action | |
} | |
} | |
typealias RefreshControlAction = ((UIRefreshControl) -> Void) | |
var pullToRefresh: (RefreshControlAction)? { | |
set(newValue) { | |
agRefreshControl.removeTarget(self, action: #selector(refreshAction(_:)), for: .valueChanged) | |
var wrapper: ActionWrapper? = nil | |
if let newValue = newValue { | |
wrapper = ActionWrapper(action: newValue) | |
agRefreshControl.addTarget(self, action: #selector(refreshAction(_:)), for: .valueChanged) | |
} | |
objc_setAssociatedObject(self, &AssociatedKeys.ActionKey, wrapper, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) | |
} | |
get { | |
guard let wrapper = objc_getAssociatedObject(self, &AssociatedKeys.ActionKey) as? ActionWrapper else { | |
return nil | |
} | |
return wrapper.action | |
} | |
} | |
var agRefreshControl: UIRefreshControl { | |
if #available(iOS 10.0, *) { | |
if let refreshView = self.refreshControl { | |
return refreshView | |
} | |
else{ | |
self.refreshControl = UIRefreshControl() | |
return self.refreshControl! | |
} | |
} | |
else{ | |
if let refreshView = backgroundView as? UIRefreshControl { | |
return refreshView | |
} | |
else{ | |
backgroundView = UIRefreshControl() | |
return UIRefreshControl() | |
} | |
} | |
} | |
func endRefreshing() { | |
self.agRefreshControl.endRefreshing() | |
} | |
func beginRefreshing() { | |
self.agRefreshControl.beginRefreshing() | |
} | |
@objc private func refreshAction(_ refreshControl: UIRefreshControl) { | |
if let action = pullToRefresh { | |
action(refreshControl) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example :-