UITableView+NoDataView.m

#import "UITableView+NoDataView.h"
#import "NoDataView.h"
#import <objc/runtime.h> @protocol TableViewDelegate <NSObject>
@optional
- (UIView *)noDataView;
- (UIImage *)noDataViewImage;
- (NSString *)noDataViewMessage;
- (UIColor *)noDataViewMessageColor;
- (NSNumber *)noDataViewCenterYOffset; @end @implementation UITableView (NoDataView) + (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method reloadData = class_getInstanceMethod(self, @selector(reloadData));
Method replace_reloadData = class_getInstanceMethod(self, @selector(replace_reloadData));
method_exchangeImplementations(reloadData, replace_reloadData); Method dealloc = class_getInstanceMethod(self, NSSelectorFromString(@"dealloc"));
Method replace_dealloc = class_getInstanceMethod(self, @selector(replace_dealloc));
method_exchangeImplementations(dealloc, replace_dealloc);
});
} - (void)replace_reloadData {
[self replace_reloadData]; // 忽略第一次加载
if (![self isInitFinish]) {
[self havingData:YES];
[self setIsInitFinish:YES];
return ;
} // 刷新完成之后检测数据量
dispatch_async(dispatch_get_main_queue(), ^{ NSInteger numberOfSections = [self numberOfSections];
BOOL havingData = NO;
for (NSInteger i = ; i < numberOfSections; i++) {
if ([self numberOfRowsInSection:i] > ) {
havingData = YES;
break;
}
} [self havingData:havingData];
});
} /**
展示占位图
*/
- (void)havingData:(BOOL)havingData { // 不需要显示占位图
if (havingData) {
[self freeNoDataViewIfNeeded];
self.backgroundView = nil;
return ;
} // 不需要重复创建
if (self.backgroundView) {
return ;
} // 自定义了占位图
if ([self.delegate respondsToSelector:@selector(noDataView)]) {
self.backgroundView = [self.delegate performSelector:@selector(noDataView)];
return ;
} // 使用自带的
UIImage * img = nil;
NSString * msg = @"暂无数据";
UIColor * color = [UIColor lightGrayColor];
CGFloat offset = ; // 获取图片
if ([self.delegate respondsToSelector:@selector(noDataViewImage)]) {
img = [self.delegate performSelector:@selector(noDataViewImage)];
}
// 获取文字
if ([self.delegate respondsToSelector:@selector(noDataViewMessage)]) {
msg = [self.delegate performSelector:@selector(noDataViewMessage)];
}
// 获取颜色
if ([self.delegate respondsToSelector:@selector(noDataViewMessageColor)]) {
color = [self.delegate performSelector:@selector(noDataViewMessageColor)];
}
// 获取偏移量
if ([self.delegate respondsToSelector:@selector(noDataViewCenterYOffset)]) {
offset = [[self.delegate performSelector:@selector(noDataViewCenterYOffset)] floatValue];
} // 创建占位图
self.backgroundView = [self defaultNoDataViewWithImage :img message:msg color:color offsetY:offset];
} /**
默认的占位图
*/
- (UIView *)defaultNoDataViewWithImage:(UIImage *)image message:(NSString *)message color:(UIColor *)color offsetY:(CGFloat)offset { // 计算位置, 垂直居中, 图片默认中心偏上.
CGFloat sW = self.bounds.size.width;
CGFloat cX = sW / ;
CGFloat cY = self.bounds.size.height * ( - 0.618) + offset;
CGFloat iW = image.size.width;
CGFloat iH = image.size.height; // 图片
UIImageView *imgView = [[UIImageView alloc] init];
imgView.frame = CGRectMake(cX - iW / , cY - iH / , iW, iH);
imgView.image = image; // 文字
UILabel *label = [[UILabel alloc] init];
label.font = [UIFont systemFontOfSize:];
label.textColor = color;
label.text = message;
label.textAlignment = NSTextAlignmentCenter;
label.frame = CGRectMake(, CGRectGetMaxY(imgView.frame) + , sW, label.font.lineHeight); // 视图
NoDataView *view = [[NoDataView alloc] init];
[view addSubview:imgView];
[view addSubview:label]; // 实现跟随 TableView 滚动
[view addObserver:self forKeyPath:kNoDataViewObserveKeyPath options:NSKeyValueObservingOptionNew context:nil];
return view;
} /**
监听
*/
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if ([keyPath isEqualToString:kNoDataViewObserveKeyPath]) { /**
在 TableView 滚动 ContentOffset 改变时, 会同步改变 backgroundView 的 frame.origin.y
可以实现, backgroundView 位置相对于 TableView 不动, 但是我们希望
backgroundView 跟随 TableView 的滚动而滚动, 只能强制设置 frame.origin.y 永远为 0
兼容 MJRefresh
*/
CGRect frame = [[change objectForKey:NSKeyValueChangeNewKey] CGRectValue];
if (frame.origin.y != ) {
frame.origin.y = ;
self.backgroundView.frame = frame;
}
}
} #pragma mark - 属性 // 加载完数据的标记属性名
static NSString * const kTableViewPropertyInitFinish = @"kTableViewPropertyInitFinish"; /**
设置已经加载完成数据了
*/
- (void)setIsInitFinish:(BOOL)finish {
objc_setAssociatedObject(self, &kTableViewPropertyInitFinish, @(finish), OBJC_ASSOCIATION_ASSIGN);
} /**
是否已经加载完成数据
*/
- (BOOL)isInitFinish {
id obj = objc_getAssociatedObject(self, &kTableViewPropertyInitFinish);
return [obj boolValue];
} /**
移除 KVO 监听
*/
- (void)freeNoDataViewIfNeeded { if ([self.backgroundView isKindOfClass:[NoDataView class]]) {
[self.backgroundView removeObserver:self forKeyPath:kNoDataViewObserveKeyPath context:nil];
}
} - (void)replace_dealloc {
[self freeNoDataViewIfNeeded];
[self replace_dealloc];
NSLog(@"TableView 视图正常销毁");
} @end

UICollectionView+NoDataView.m

#import "UICollectionView+NoDataView.h"
#import <objc/runtime.h>
#import "NoDataView.h" /**
消除警告
*/
@protocol CollectionViewDelegate <NSObject>
@optional
- (UIView *)noDataView;
- (UIImage *)noDataViewImage;
- (NSString *)noDataViewMessage;
- (UIColor *)noDataViewMessageColor;
- (NSNumber *)noDataViewCenterYOffset;
@end @implementation UICollectionView (NoDataView)
/**
加载时, 交换方法
*/
+ (void)load {
// 只交换一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ Method reloadData = class_getInstanceMethod(self, @selector(reloadData));
Method replace_reloadData = class_getInstanceMethod(self, @selector(replace_reloadData));
method_exchangeImplementations(reloadData, replace_reloadData); Method dealloc = class_getInstanceMethod(self, NSSelectorFromString(@"dealloc"));
Method replace_dealloc = class_getInstanceMethod(self, @selector(replace_dealloc));
method_exchangeImplementations(dealloc, replace_dealloc);
});
} /**
在 ReloadData 的时候检查数据
*/
- (void)replace_reloadData { [self replace_reloadData]; // 忽略第一次加载
if (![self isInitFinish]) {
[self havingData:YES];
[self setIsInitFinish:YES];
return ;
}
// 刷新完成之后检测数据量
dispatch_async(dispatch_get_main_queue(), ^{ NSInteger numberOfSections = [self numberOfSections];
BOOL havingData = NO;
for (NSInteger i = ; i < numberOfSections; i++) {
if ([self numberOfItemsInSection:i] > ) {
havingData = YES;
break;
}
} [self havingData:havingData];
});
} /**
展示占位图
*/
- (void)havingData:(BOOL)havingData { // 不需要显示占位图
if (havingData) {
[self freeNoDataViewIfNeeded];
self.backgroundView = nil;
return ;
} // 不需要重复创建
if (self.backgroundView) {
return ;
} // 自定义了占位图
if ([self.delegate respondsToSelector:@selector(noDataView)]) {
self.backgroundView = [self.delegate performSelector:@selector(noDataView)];
return ;
} // 使用自带的
UIImage *img = nil;
NSString *msg = @"暂无数据";
UIColor *color = [UIColor lightGrayColor];
CGFloat offset = ; // 获取图片
if ([self.delegate respondsToSelector:@selector(noDataViewImage)]) {
img = [self.delegate performSelector:@selector(noDataViewImage)];
}
// 获取文字
if ([self.delegate respondsToSelector:@selector(noDataViewMessage)]) {
msg = [self.delegate performSelector:@selector(noDataViewMessage)];
}
// 获取颜色
if ([self.delegate respondsToSelector:@selector(noDataViewMessageColor)]) {
color = [self.delegate performSelector:@selector(noDataViewMessageColor)];
}
// 获取偏移量
if ([self.delegate respondsToSelector:@selector(noDataViewCenterYOffset)]) {
offset = [[self.delegate performSelector:@selector(noDataViewCenterYOffset)] floatValue];
} // 创建占位图
self.backgroundView = [self defaultNoDataViewWithImage :img message:msg color:color offsetY:offset];
} /**
默认的占位图
*/
- (UIView *)defaultNoDataViewWithImage:(UIImage *)image message:(NSString *)message color:(UIColor *)color offsetY:(CGFloat)offset { // 计算位置, 垂直居中, 图片默认中心偏上.
CGFloat sW = self.bounds.size.width;
CGFloat cX = sW / ;
CGFloat cY = self.bounds.size.height * ( - 0.618) + offset;
CGFloat iW = image.size.width;
CGFloat iH = image.size.height; // 图片
UIImageView *imgView = [[UIImageView alloc] init];
imgView.frame = CGRectMake(cX - iW / , cY - iH / , iW, iH);
imgView.image = image; // 文字
UILabel *label = [[UILabel alloc] init];
label.font = [UIFont systemFontOfSize:];
label.textColor = color;
label.text = message;
label.textAlignment = NSTextAlignmentCenter;
label.frame = CGRectMake(, CGRectGetMaxY(imgView.frame) + , sW, label.font.lineHeight); // 视图
NoDataView * view = [[NoDataView alloc] init];
[view addSubview:imgView];
[view addSubview:label]; // 实现跟随 collectionView 滚动
[view addObserver:self forKeyPath:kNoDataViewObserveKeyPath options:NSKeyValueObservingOptionNew context:nil];
return view;
} /**
监听
*/
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if ([keyPath isEqualToString:kNoDataViewObserveKeyPath]) { /**
在 collectionView 滚动 ContentOffset 改变时, 会同步改变 backgroundView 的 frame.origin.y
可以实现, backgroundView 位置相对于 collectionView 不动, 但是我们希望
backgroundView 跟随 collectionView 的滚动而滚动, 只能强制设置 frame.origin.y 永远为 0
兼容 MJRefresh
*/
CGRect frame = [[change objectForKey:NSKeyValueChangeNewKey] CGRectValue];
if (frame.origin.y != ) {
frame.origin.y = ;
self.backgroundView.frame = frame;
}
}
} #pragma mark - 属性 /// 加载完数据的标记属性名
static NSString * const kCollectionViewPropertyInitFinish = @"kCollectionViewPropertyInitFinish"; /**
设置已经加载完成数据了
*/
- (void)setIsInitFinish:(BOOL)finish {
objc_setAssociatedObject(self, &kCollectionViewPropertyInitFinish, @(finish), OBJC_ASSOCIATION_ASSIGN);
} /**
是否已经加载完成数据
*/
- (BOOL)isInitFinish {
id obj = objc_getAssociatedObject(self, &kCollectionViewPropertyInitFinish);
return [obj boolValue];
} /**
移除 KVO 监听
*/
- (void)freeNoDataViewIfNeeded { if ([self.backgroundView isKindOfClass:[NoDataView class]]) {
[self.backgroundView removeObserver:self forKeyPath:kNoDataViewObserveKeyPath context:nil];
}
} - (void)replace_dealloc {
[self freeNoDataViewIfNeeded];
[self replace_dealloc];
NSLog(@"CollectionView 视图正常销毁");
}
@end

NoDataView.h

#import <UIKit/UIKit.h>

extern NSString * const kNoDataViewObserveKeyPath;

@interface NoDataView : UIView

@end

NoDataView.m

#import "NoDataView.h"
NSString * const kNoDataViewObserveKeyPath = @"frame";
@implementation NoDataView - (void)dealloc {
NSLog(@"占位视图正常销毁");
} @end

调用

#import "ViewController.h"
#import "MJRefresh.h" @interface ViewController () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) NSMutableArray * dataArr;
@end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
self.tableView.delegate = self;
self.tableView.dataSource = self;
[self.view addSubview:self.tableView];
self.tableView.tableFooterView = [UIView new]; __weak typeof(self) weakSelf = self;
self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
[weakSelf loadData];
}];
} - (void)loadData {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.tableView.mj_header endRefreshing];
[self.tableView reloadData];
});
} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return ;
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
return [UITableViewCell new];
} #pragma mark - TableView 占位图 - (UIImage *)noDataViewImage {
return [UIImage imageNamed:@"note_list_no_data"];
} - (NSString *)noDataViewMessage {
return @"都用起来吧, 起飞~";
} - (UIColor *)noDataViewMessageColor {
return [UIColor blackColor];
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end

TableView 无数据时展示占位视图的更多相关文章

  1. IOS-当遇到tableView整体上移时的解决方案

    方案一在使用了navigationController后,当界面进行跳转往返后,时而会出现tableView或collectionView上移的情况,通常会自动上移64个像素,那么这种情况,我们可以关 ...

  2. IOS开发-当遇到tableView整体上移时的解决方案

    方案一在使用了navigationController后,当界面进行跳转往返后,时而会出现tableView上移的情况,通常会自动上移64个像素,那么这种情况,我们可以关闭tableView的自动适配 ...

  3. iOS开发之--当遇到tableView整体上移时的解决方案

    方案一在使用了navigationController后,当界面进行跳转往返后,时而会出现tableView上移的情况,通常会自动上移64个像素,那么这种情况,我们可以关闭tableView的自动适配 ...

  4. iOS UIScrollView 滚动到当前展示的视图居中展示

    需求展示: 测试效果1 first uiscrollView  宽度 为屏幕宽度   滚动步长 为 scroll 宽度的1/3   分析: 这个是最普通版 无法使每一次滚动的结果子视图居中展示, WA ...

  5. 看代码学知识之(2) ListView无数据时显示其他View

    看代码学知识之(2) ListView无数据时显示其他View 今天看的一块布局是这样的: <!-- The frame layout is here since we will be show ...

  6. 父视图 使用 UIViewAnimationWithBlocks 时,如何让子视图无动画

    tableView使用 UIViewAnimationWithBlocks 时 上面的cell也会一起出现动画, 所以在设置cell的时候 添加 [UIView performWithoutAnima ...

  7. 刷新SQL Server所有视图、函数、存储过程 更多 sql 此脚本用于在删除或添加字段时刷新相关视图,并检查视图、函数、存储过程有效性。 [SQL]代码 --视图、存储过程、函数名称 DECLARE @NAME NVARCHAR(255); --局部游标 DECLARE @CUR CURSOR --自动修改未上状态为旷课 SET @CUR=CURSOR SCROLL DYNAMIC FO

    刷新SQL Server所有视图.函数.存储过程 更多   sql   此脚本用于在删除或添加字段时刷新相关视图,并检查视图.函数.存储过程有效性. [SQL]代码 --视图.存储过程.函数名称 DE ...

  8. [转帖]Oracle报错ORA-26563--当重命名表时碰到物化视图

    Oracle报错ORA-26563--当重命名表时碰到物化视图 https://www.toutiao.com/i6739137279115133447/ 原创 波波说运维 2019-09-26 00 ...

  9. tableView 选中cell时,获取到当前cell

    // >> 找到当前选中的cell,设置选中时的cell背景色 SideTableViewCell * cell = (SideTableViewCell *)[tableView cel ...

随机推荐

  1. chrome刷新CSS

    改动CSS发现页面根本没有变化,再三查看确实是这一处CSS,那么可能的就是浏览器缓存了CSS而刷新无效了. chrome刷新CSS: 方法1:直接ctrl+F5,进行强制刷新页面,浏览器会重新加载所有 ...

  2. 基于netty的websocket例子

    nettyServer package com.atguigu.netty.websocket; import javax.annotation.PostConstruct; import org.s ...

  3. 利用Fiddler拦截接口请求并篡改数据

    近期在测试一个下单的项目,出于安全角度考虑,测试了一个场景,那就是利用工具对接口进行拦截并篡改数据.将接口一拦截并篡改数据后,发现收货满满.开发默默接受了我的建议,并对代码进行了修改. 对于fiddl ...

  4. SpringBoot整合elasticsearch

    在这一篇文章开始之前,你需要先安装一个ElasticSearch,如果你是mac或者linux可以参考https://www.jianshu.com/p/e47b451375ea,如果是windows ...

  5. 在Xamarin.iOS项目中使用预设数据库

    在Xamarin.iOS项目中使用预设数据库 当开发者准备好一个预设数据库文件后,就可以将这个数据库文件添加到创建的项目中了.本节将分别在Xamarin.iOS和Xamarin.Android项目中使 ...

  6. 南阳325----zb的生日

    //重量太大,用01背包容易超时 //数据只有20组.可以用dfs搜索最优解 #include<stdio.h> ]; int maxs,n,s; void dfs(int,int); i ...

  7. php 操作json的各种格式

    php中操作json的函数 加密:json_encode() ,也就是把数据转成json格式 * 数组转换成json格式时,索引数组得出的结果是不带映射关系,所以都是[]:关联数组是映射,所以最外围是 ...

  8. 学不动了,ECMAScript2018都来了

    原文:ECMAScript regular expressions are getting better! 作者: Mathias Bynens: Google V8引擎开发者 译者:Fundebug ...

  9. 关于在ViewPager的子页面中不能跳转的问题

    关于在ViewPager的子页面中不能跳转的问题 什么是ViewPager? 相信很多人使用过微信,其实微信的四个子页面:微信.通讯录.发现.我以及下面的引导空间就是ViewPager. 出现的问题: ...

  10. vim技巧3

    yyp复制当前行到下一行ddp剪切当前行到下一行cw:删除当前单词并进入插入模式xp:交换当前字符和右边字符s:删除光标所在的字符并进入插入模式I:在行首开始输入文字并进入插入模式A:在行尾开始输入文 ...