Skip to content

Instantly share code, notes, and snippets.

@AshvinGudaliya
Last active July 17, 2018 11:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AshvinGudaliya/2e0865b108c2360bcaf12da404d54ee8 to your computer and use it in GitHub Desktop.
Save AshvinGudaliya/2e0865b108c2360bcaf12da404d54ee8 to your computer and use it in GitHub Desktop.
PullToRefresh using UIRefreshControl directly property type.
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)
}
}
}
@AshvinGudaliya
Copy link
Author

Example :-

yourTableView.pullToRefresh = { refCon in
         //Do Something
}

yourTableView.agRefreshControl this is a UIRefreshControl

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment