2句代码添加上下拉刷新
scrollView.hw_hearderRefreshBlock = { // 下拉刷新
// 你的逻辑
}
scrollView.hw_footerRefreshBlock = { // 上拉刷新
// 你的逻辑
}
使用案例
override func viewDidLoad() {
super.viewDidLoad()
let scrollView = UIScrollView.init(frame: self.view.bounds)
scrollView.backgroundColor = UIColor.white
scrollView.hw_hearderRefreshBlock = { // 下拉刷新
DispatchQueue.main.asyncAfter(deadline: .now()+0.3, execute: {
print("下拉刷新结束")
scrollView.endRefreshing()
})
}
scrollView.hw_footerRefreshBlock = { // 上拉刷新
DispatchQueue.main.asyncAfter(deadline: .now()+0.3, execute: {
print("上拉刷新结束")
scrollView.endRefreshing()
})
}
scrollView.beginRefreshing()
view.addSubview(scrollView)
}
image.png
实现原理:
主要是通过
Runtime
给UIScrollView
添加2个闭包
,在需要调用闭包是判断UIScrollView
对应的mj_header
与mj_footer
是否存在,不存在给其添加对应的属性,下面还是看代码吧
import UIKit
import MJRefresh
extension UIScrollView {
private struct RuntimeKey {
static let HearderRefreshBlockKey = UnsafeRawPointer.init(bitPattern: "HearderRefreshBlockKey".hashValue)
static let FooterRefreshBlockKey = UnsafeRawPointer.init(bitPattern: "FooterRefreshBlockKey".hashValue)
}
/// 下拉刷新的回调
var hw_hearderRefreshBlock: (()->())? {
set {
if mj_header == nil { addHearderRefresh() } // 如果不存在 就自动添加
objc_setAssociatedObject(self, UIScrollView.RuntimeKey.HearderRefreshBlockKey!, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, UIScrollView.RuntimeKey.HearderRefreshBlockKey!) as? (()->())
}
}
/// 上拉刷新的回调
var hw_footerRefreshBlock: (()->())? {
set {
if mj_footer == nil { addFooterRefresh() } // 如果不存在 就自动添加
objc_setAssociatedObject(self, UIScrollView.RuntimeKey.FooterRefreshBlockKey!, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, UIScrollView.RuntimeKey.FooterRefreshBlockKey!) as? (()->())
}
}
/// 单独使用下拉刷新
private func addHearderRefresh() {
let header = MJRefreshNormalHeader { [weak self] in
if self == nil {return}
if self?.mj_footer?.isRefreshing == true { // 如果上拉正在执行 将其结束
self?.mj_footer?.endRefreshing()
}
if self?.mj_header?.isRefreshing == true {
if self?.hw_hearderRefreshBlock == nil {return}
self?.hw_hearderRefreshBlock!()
}
}
mj_header = header
}
/// 单独使用上拉刷新
private func addFooterRefresh() {
let footer = MJRefreshBackNormalFooter { [weak self] in
if self == nil {return}
if self?.mj_header?.isRefreshing == true { // 如果下拉正在执行 将其结束
self?.mj_header?.endRefreshing()
}
if self?.mj_footer?.isRefreshing == true {
if self?.hw_footerRefreshBlock == nil {return}
self?.hw_footerRefreshBlock!()
}
}
mj_footer = footer
}
/// 结束刷新
open func endRefreshing() {
if mj_footer?.isRefreshing == true {
mj_footer?.endRefreshing()
}
if mj_header?.isRefreshing == true {
mj_header?.endRefreshing()
}
}
/// 开始刷新
open func beginRefreshing() {
mj_header?.beginRefreshing()
}
}
网友评论