零行代碼實現(xiàn)tableView、collectionView無數(shù)據(jù)時展示占位圖,同時可以進(jìn)行簡單的自定義,或者完全自定義, 考慮了有tableHeaderView的情況。使用協(xié)議模式實現(xiàn)自定義方法。拖入工程即可使用。
loading菊花提示:
# import "UITableView+PlaceHolder.h"
...
tableView.loading = YES;//顯示菊花
tableView.loading = NO;//隱藏菊花
...
具體代碼請移步:GitHub Demo地址
功能實現(xiàn)的核心是利用runtime替換系統(tǒng)的reloadData方法。
/** 加載時, 交換方法 ,類加載時會調(diào)用該方法*/
+ (void)load {
// 只交換一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method reloadData = class_getInstanceMethod(self, @selector(reloadData));
Method sp_reloadData = class_getInstanceMethod(self, @selector(sp_reloadData));
method_exchangeImplementations(reloadData, sp_reloadData);
Method dealloc = class_getInstanceMethod(self, NSSelectorFromString(@"dealloc"));
Method sp_dealloc = class_getInstanceMethod(self, @selector(sp_dealloc));
method_exchangeImplementations(dealloc, sp_dealloc);
});
}
通過tableView的代理方法判斷是不是有數(shù)據(jù)
// 刷新完成之后檢測數(shù)據(jù)量
dispatch_async(dispatch_get_main_queue(), ^{
NSInteger numberOfSections = [self numberOfSections];
BOOL havingData = NO;
for (NSInteger i = 0; i < numberOfSections; i++) {
if ([self numberOfRowsInSection:i] > 0) {
havingData = YES;
break;
}
)
});
默認(rèn)顯示一行文字:暫無數(shù)據(jù)??梢詫崿F(xiàn)點擊事件代理方法:
#pragma mark - 默認(rèn)的占位圖點擊事件(完全自定義的view自己加點擊事件就好了)
- (void)sp_placeHolderViewClick {
NSLog(@"點擊了重新加載");
}
自定義時實現(xiàn)如下代理方法:
/** 完全自定義 */
- (UIView *)sp_placeHolderView {
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 100)];
label.backgroundColor = [UIColor cyanColor];
label.text = @"這是一個自定義的View";
label.textAlignment = NSTextAlignmentCenter;
return label;
}
/** 只自定義圖片 */
- (UIImage *)sp_placeHolderImage {
return [UIImage imageNamed:@"note_list_no_data"];
}
/** 只自定義文字 */
- (NSString *)sp_placeHolderMessage {
return @"自定義的無數(shù)據(jù)提示";
}
/** 只自定義文字顏色 */
- (UIColor *)sp_placeHolderMessageColor {
return [UIColor orangeColor];
}
/** 只自定義偏移量 */
- (NSNumber *)sp_placeHolderViewCenterYOffset {
return @(0);
}