您的位置:首页 > 产品设计 > UI/UE

IOS开发- UITableView 无数据时,显示“暂无数据”背景的实现

2017-11-16 14:07 543 查看
需求:

当UITableView 无数据时,当前耳界面的背景界面显示“暂无数据”。

方法1:

我们可以用 Objective-C 的分类 (Catergory) 来解决这类问题。

具体实现过程:

步骤1. 我们对UITableView进行类扩展

操作:File > New > File > IOS > Objective-C File > Next > File:EmptyTipLabel File Type:Catergory Class:UITableView > Next

代码:

// .h文件
@import UIKit;

@interface UITableView (EmptyData)
//添加一个方法
- (void) tableViewDisplayWitMsg:(NSString *) message ifNecessaryForRowCount:(NSUInteger) rowCount;

@end

/// .m文件
#import "UITableView+EmptyData.h"

@implementation UITableView (EmptyData)

- (void) tableViewDisplayWitMsg:(NSString *) message ifNecessaryForRowCount:(NSUInteger) rowCount
{
if (rowCount == 0) {
// Display a message when the table is empty
// 没有数据的时候,UILabel的显示样式
UILabel *messageLabel = [UILabel new];

messageLabel.text = message;
messageLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
messageLabel.textColor = [UIColor lightGrayColor];
messageLabel.textAlignment = NSTextAlignmentCenter;
[messageLabel sizeToFit];

self.backgroundView = messageLabel;
self.separatorStyle = UITableViewCellSeparatorStyleNone;
} else {
self.backgroundView = nil;
self.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
}
}

@end

步骤2:导入头文件

#import "UITableView+EmptyData.h"

在UITableView的数据源方法中进行调用就可以了。如果你的TableView有多个Section,那么可以在-
(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView方法中进行调用。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
/**
*  如果没有数据的时候提示用户的信息
*/
[tableView tableViewDisplayWitMsg:@"没有查询到相对应的商品" ifNecessaryForRowCount:self.dataSource.count];
return [self.dataSource count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}

如果你的TableView只有一个分组,那么可以在-
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 中进行调用

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
[tableView tableViewDisplayWitMsg:@"没有查询到相对应的商品" ifNecessaryForRowCount:self.dataSource.count];
return self.dataSource.count;
}


方法2
:继承UITableView,再新类中集成图片和文字

#import <UIKit/UIKit.h>
#import "Const.h"

@interface WFEmptyTableView : UITableView

@property (nonatomic, assign) BOOL showEmptyTipView; // 是否显示背景提示文字
@property (nonatomic, assign) NSInteger vOffset;
@property (nonatomic, copy) NSString *tipString;     // 提示文字
@property (nonatomic, copy) NSString *tipImageName;  // 提示图片

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: