@interface UITableView (PlaceholderView)
@property(nonatomic,strong)UIView *emptyView;
@end
#import "UITableView+PlaceholderView.h"
#import <objc/runtime.h>
@implementation UITableView (PlaceholderView)
#pragma mark ----------------------- emptyView set 方法 ------------------------
-(void)setEmptyView:(UIView *)emptyView
{
objc_setAssociatedObject(self, @selector(emptyView), emptyView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if (objc_getAssociatedObject(self, @selector(emptyView)))
{
//防止手动调用load出现多次调用的情况:
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSLog(@"刷新啊啊");
[UITableView swizzleOriginMethod:@selector(reloadData) Method:@selector(newReloadData)];
});
}
}
#pragma mark ----------------------- 自定义刷新方法 ------------------------
-(void)newReloadData
{
[self checkIsEmpty];
[self newReloadData];
}
#pragma mark ----------------------- emptyView 懒加载 ------------------------
-(UIView *)emptyView
{
return objc_getAssociatedObject(self, @selector(emptyView));
}
#pragma mark ----------------------- 替换系统刷新 ------------------------
+ (void)swizzleOriginMethod:(SEL)oriSel Method:(SEL)newSel
{
Method oldMethod = class_getInstanceMethod(self, oriSel);//旧方法
Method newMethod = class_getInstanceMethod(self, newSel);//新方法
BOOL methodIsAdd = class_addMethod(self, oriSel, method_getImplementation(newMethod), method_getTypeEncoding(newMethod));
if (methodIsAdd)
{
class_replaceMethod(self, newSel, method_getImplementation(oldMethod), method_getTypeEncoding(oldMethod));
}
else
{
method_exchangeImplementations(oldMethod, newMethod);
}
}
#pragma mark ----------------------- 新刷新 ------------------------
- (void)checkIsEmpty
{
BOOL isEmpty = YES;
if ([self.dataSource respondsToSelector:@selector(numberOfSectionsInTableView:)])
{
NSInteger sections = [self.dataSource numberOfSectionsInTableView:self];
if (sections > 0)
{
isEmpty = NO;
}
}
else
{
NSInteger rows = [self.dataSource tableView:self numberOfRowsInSection:0];
if (rows > 0)
{
isEmpty = NO;
}
}
if (isEmpty)
{
[self.emptyView removeFromSuperview];
[self addSubview:self.emptyView];
}
else
{
[self.emptyView removeFromSuperview];
}
}
@end
// 调用
#import "UITableView+PlaceholderView.h"
@interface ViewController ()
@property (nonatomic, strong) UITableView *tableView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIView *placeholderView = [[UIView alloc]initWithFrame:self.view.bounds];
placeholderView.backgroundColor = [UIColor redColor];
[self.view addSubview:self.tableView];
self.tableView.emptyView = placeholderView;
}
-(UITableView *)tableView{
if (!_tableView) {
_tableView = [[UITableView alloc]initWithFrame:self.view.bounds];
_tableView.backgroundColor = [UIColor blueColor];
}
return _tableView;
}