在開發過程中,我們經常會做到一些列表,當列表有數據的時候顯示數據,而當列表沒有數據或者網絡錯誤的時候就顯得空蕩蕩的,此時需要我們加上一個缺省頁面,如頭條:
我們的做法用到了UITableView的backgroundView屬性
創建UITableView的category
@interface UITableView (LKCategory)
/**
根據count顯示s提示信息(無數據,網絡不可用,網絡請求失敗)
@param count 個數
*/
- (void)showDataCount:(NSInteger)count;
@end
@implementation UITableView (LKCategory)
- (void)showDataCount:(NSInteger)count{
if (count > 0) {
self.backgroundView = nil;
return;
}
UIView *backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.width, self.height)];
UIImageView *showImageView = [[UIImageView alloc]init];
showImageView.contentMode = UIViewContentModeScaleAspectFill;
[backgroundView addSubview:showImageView];
UILabel *tipLabel = [UILabel labelWithFont:systemFont(15) textColor:kColor999999];
tipLabel.textAlignment = NSTextAlignmentCenter;
[backgroundView addSubview:tipLabel];
showImageView.image = [UIImage imageNamed:@"image_noData"];
tipLabel.text = @"暫無數據";
///tipLabel.text = @"網絡不可用";
[showImageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerX.mas_equalTo(backgroundView.mas_centerX);
make.centerY.mas_equalTo(backgroundView.mas_centerY).mas_offset(-20);
}];
[tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerX.mas_equalTo(backgroundView.mas_centerX);
make.top.mas_equalTo(showImageView.mas_bottom).mas_offset(30);
}];
self.backgroundView = backgroundView;
}
然後在網絡請求中調用方法就行了
///網絡請求返回
///......
[self.tableView showDataCount:self.totalSize];
///......
此時就實現了當列表有數據的時候顯示數據,無數據顯示缺省頁面