QMUI_iOS上拉加载更多:QMUITableView扩展实践
【免费下载链接】QMUI_iOS 项目地址: https://gitcode.com/gh_mirrors/qmu/QMUI_iOS
在iOS应用开发中,上拉加载更多是提升用户体验的关键功能。QMUI_iOS框架通过QMUIKit/QMUIComponents/QMUITableView.h和QMUIKit/UIKitExtensions/UITableView+QMUI.h提供了完整的解决方案,让开发者无需重复造轮子。
核心功能解析
QMUI_iOS的上拉加载能力基于两个核心组件构建:
-
QMUITableView:继承自系统UITableView,重写了
setTableFooterView:方法确保始终存在footerView,避免内容不满一屏时的空白分割线问题。- (void)setTableFooterView:(UIView *)tableFooterView { if (!tableFooterView) { tableFooterView = [[UIView alloc] init]; } [super setTableFooterView:tableFooterView]; } -
UITableView+QMUI分类:提供了丰富的工具方法,包括:
qmui_realContentSize:获取真实内容大小,解决系统contentSize在searchBar场景下不准确的问题qmui_canScroll:判断列表是否可滚动,为加载更多触发条件提供依据qmui_cellVisibleAtIndexPath::检查cell是否在可视区域
实现步骤
1. 初始化QMUITableView
self.tableView = [[QMUITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
self.tableView.delegate = self;
self.tableView.dataSource = self;
[self.view addSubview:self.tableView];
2. 配置加载更多视图
推荐使用QMUI自带的QMUIEmptyView作为加载状态指示器:
self.loadMoreView = [[QMUIEmptyView alloc] init];
self.loadMoreView.loadingViewStyle = QMUIActivityIndicatorViewStyleSmall;
self.tableView.tableFooterView = self.loadMoreView;
3. 实现滚动监听
通过UIScrollViewDelegate监听滚动事件,判断是否触发加载更多:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (self.isLoadingMore) return;
CGFloat contentOffsetY = scrollView.contentOffset.y;
CGFloat contentHeight = scrollView.contentSize.height;
CGFloat frameHeight = scrollView.frame.size.height;
CGFloat bottomInset = scrollView.contentInset.bottom;
// 当滚动到距离底部200pt时触发加载
if (contentOffsetY + frameHeight + bottomInset >= contentHeight - 200) {
[self loadMoreData];
}
}
4. 加载更多逻辑实现
- (void)loadMoreData {
self.isLoadingMore = YES;
self.loadMoreView.hidden = NO;
// 模拟网络请求
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// 添加新数据
[self.dataArray addObjectsFromArray:newData];
[self.tableView reloadData];
// 加载完成
self.isLoadingMore = NO;
self.loadMoreView.hidden = YES;
// 如果没有更多数据,可设置为结束状态
if (noMoreData) {
self.tableView.tableFooterView = [[UIView alloc] init];
}
});
}
高级用法
自定义加载更多视图
如果需要定制加载更多样式,可以创建自定义UIView并通过tableFooterView设置:
self.customLoadMoreView = [[CustomLoadMoreView alloc] init];
self.tableView.tableFooterView = self.customLoadMoreView;
结合QMUIStaticTableView使用
对于静态列表,可以使用UITableView+QMUIStaticCell分类简化实现:
[self.tableView qmui_addStaticCellsWithDataArray:staticDataArray];
注意事项
-
性能优化:避免在
scrollViewDidScroll:中执行复杂计算,可通过节流方式优化 -
边界处理:使用
qmui_realContentSize替代系统contentSize,确保在searchBar场景下的准确性:CGFloat contentHeight = self.tableView.qmui_realContentSize.height; -
空数据处理:结合QMUIEmptyView实现无数据状态展示
QMUI_iOS的上拉加载方案已在众多生产环境中验证,通过QMUIConfigurationTemplate还可以实现全局样式统一配置,为应用开发提供高效支持。
【免费下载链接】QMUI_iOS 项目地址: https://gitcode.com/gh_mirrors/qmu/QMUI_iOS
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



