iOS UITableView 无数据占位视图
2019-04-15 本文已影响0人
索性流年
新建扩展UITableView的Category 名为 LyEmptyData
.h
//如果出现个别页面无背景图情况,可以手动调用该方法,否则无需调用
-(void)loadBackground;
.m
+(void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
@autoreleasepool {
[self swizzleMethod:@selector(reloadData) withMethod:@selector(ly_reloadData) error:nil];
};
});
}
#pragma mark - 替换系统方法
-(void)ly_reloadData{
[self ly_reloadData];
[self loadBackground];
}
#pragma mark - 实现自定义背景判断
-(void)loadBackground{
if (![self isMemberOfClass:[UITableView class]]) {
self.backgroundView = nil;
return;
}
if (self.visibleCells.count <= 0 && self.numberOfSections <= 1) {
if (self.tableHeaderView == nil && self.tableFooterView == nil) {
NSLog(@"%ld",(long)self.numberOfSections);
// 没有数据的时候,UILabel的显示样式
UITableViewBackgroundView * messageBackgroundView = [UITableViewBackgroundView new];
self.backgroundView = messageBackgroundView;
self.separatorStyle = UITableViewCellSeparatorStyleNone;
}
} else {
self.backgroundView = nil;
}
}
#pragma mark - 设置系统交换
+ (BOOL)swizzleMethod:(SEL)originalSelector withMethod:(SEL)swizzledSelector error:(NSError **)error
{
Method originalMethod = class_getInstanceMethod(self, originalSelector);
if (!originalMethod) {
NSString *string = [NSString stringWithFormat:@" %@ 类没有找到 %@ 方法",NSStringFromClass([self class]),NSStringFromSelector(originalSelector)];
*error = [NSError errorWithDomain:@"NSCocoaErrorDomain" code:-1 userInfo:[NSDictionary dictionaryWithObject:string forKey:NSLocalizedDescriptionKey]];
return NO;
}
Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector);
if (!swizzledMethod) {
NSString *string = [NSString stringWithFormat:@" %@ 类没有找到 %@ 方法",NSStringFromClass([self class]),NSStringFromSelector(swizzledSelector)];
*error = [NSError errorWithDomain:@"NSCocoaErrorDomain" code:-1 userInfo:[NSDictionary dictionaryWithObject:string forKey:NSLocalizedDescriptionKey]];
return NO;
}
if (class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)))
{
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
return YES;
}