iOS UITableView 无数据占位图
2019-01-22 本文已影响8人
赵哥窟
在使用TableView的时候,经常会遇到一些无数据需要用到占位图的情况,所以就写一个控件来实现。
思路:使用UITableView Category来实现,由于占位图式样多种多样,所以控件就不用考虑很多情况,把占位图交给外部实现,控件内部只处理有数据和没有数据显示占位图即可。
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@protocol DTableViewPlaceHolderDelegate <NSObject>
@required
/**
无数据占位图
@return 占位图
*/
- (UIView *)makePlaceHolderView;
@optional
/**
出现占位图的时候TableView是否能拖动
@return BOOL
*/
- (BOOL)enableScrollWhenPlaceHolderViewShowing;
@end
@interface UITableView (PlaceHolder)
- (void)d_reloadData;
@end
NS_ASSUME_NONNULL_END
#import "UITableView+PlaceHolder.h"
#import <objc/runtime.h>
@interface UITableView ()
/**占位图*/
@property (nonatomic, strong) UIView *placeHolderView;
@end
@implementation UITableView (PlaceHolder)
- (UIView *)placeHolderView {
return objc_getAssociatedObject(self, @selector(placeHolderView));
}
- (void)setPlaceHolderView:(UIView *)placeHolderView {
objc_setAssociatedObject(self, @selector(placeHolderView), placeHolderView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)d_reloadData {
[self reloadData];
[self d_checkEmpty];
}
- (void)d_checkEmpty {
BOOL isEmpty = YES;
id<UITableViewDataSource> src = self.dataSource;
NSInteger sections = 1;
// 获取sections
if ([src respondsToSelector: @selector(numberOfSectionsInTableView:)]) {
sections = [src numberOfSectionsInTableView:self];
}
// 获取rows
for (int i = 0; i<sections; ++i) {
NSInteger rows = [src tableView:self numberOfRowsInSection:i];
// 如果rows不为零
if (rows > 0) {
isEmpty = NO;
break;
}
}
// 如果rows为空
if (isEmpty) {
// 默认ScrollView可以滚动
BOOL scrollEnabled = YES;
if ([self respondsToSelector:@selector(enableScrollWhenPlaceHolderViewShowing)]) {
scrollEnabled = [self performSelector:@selector(enableScrollWhenPlaceHolderViewShowing)];
}
else if ([self.delegate respondsToSelector:@selector(enableScrollWhenPlaceHolderViewShowing)]) {
scrollEnabled = [self.delegate performSelector:@selector(enableScrollWhenPlaceHolderViewShowing)];
}
self.scrollEnabled = scrollEnabled;
// 移除placeHolderView
[self.placeHolderView removeFromSuperview];
// 获取placeHolderView
if ([self respondsToSelector:@selector(makePlaceHolderView)]) {
self.placeHolderView = [self performSelector:@selector(makePlaceHolderView)];
}
else if ( [self.delegate respondsToSelector:@selector(makePlaceHolderView)]) {
self.placeHolderView = [self.delegate performSelector:@selector(makePlaceHolderView)];
}
self.placeHolderView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
[self addSubview:self.placeHolderView];
}
else {
// rows不为空 移除placeHolderView
[self.placeHolderView removeFromSuperview];
self.placeHolderView = nil;
// 设置TableView 可滚动
self.scrollEnabled = YES;
}
}
@end
使用时候只要调用d_reloadData方法即可。但是必须实现
- (UIView *)makePlaceHolderView ;
如果需要在没有数据的时候让TableView的拖动不可用,需要实现
- (BOOL)enableScrollWhenPlaceHolderViewShowing{
return NO;
}