前言
我们都知道几乎所有的app都会有UITableView这个控件参与,而没有数据时我们应该怎样展示给用户是很关键的一件事,不然就是白茫茫的一片,用户体验不好。比如我的项目在UITableView没有数据时提示用户“暂无数据”,我之前都是这么写的
// 显示无数据提示
1. (void)showNoDataLabel
{
if (!_noDataLabel) {
_noDataLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, ScreenHeight-150, ScreenWidth, 25)];
_noDataLabel.text = @"暂无数据";
_noDataLabel.textColor = COLOR_f15899;
_noDataLabel.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:_noDataLabel];
}
if ([self.dataSource count] == 0) {
_noDataLabel.hidden = NO;
}
else{
_noDataLabel.hidden = YES;
}
}
写一个这样的方法,每次在网络请求完成的时候,就调用上面的方法,这个方法会判断数据源数组中有没有数据,如果没有数据,那么_noDataLabel就会显示,如果有数据该_noDataLabel就继续隐藏。这样做当然没有问题,但是这样做很不合理:
1. 这是一种典型的面向过程的方法,没有进行封装,不便于维护。
2. 这样的代码没有重复利用,所用到的地方,几乎都是要拷贝一份。
3. 没有很好的利用Objective C这门编程语言的特性-分类。
4. 导致控制器的代码过多,不便于维护。
解决方法
这是我在别人博客里面看到的一种很巧妙的解决方法。利用Objective-C的分类这一特性可以很好的解决这个问题。做法如下:
首先我们对UITableView进行一个扩展(即创建一个类目),我命名为EmptyData,代码如下:
//.h文件
#import <UIKit/UIKit.h>
@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;
}
}
如何使用呢?
首先导入头文件
#import "UITableView+EmptyData.h"
然后在UITableView的数据源代理方法中使用就可以了。
a.如果你的tableView是分组的,则在下面这个数据源代理方法里面这样写就可以了。
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
/**
* 如果没有数据的时候提示用户的信息
*/
[tableView tableViewDisplayWitMsg:@"暂无数据" ifNecessaryForRowCount:self.dataSource.count];
return [self.dataSource count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 10;
}
b.如果你的tableView只有一个分组的话,则采用下面这种调用方式
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
[tableView tableViewDisplayWitMsg:@"暂无数据" ifNecessaryForRowCount:self.dataSource.count];
return self.dataSource.count;
}
效果图:
总结
只要你用得到的地方,导入这个分类就可以使用,是不是很方便呢,也不需要写重复代码,还易于维护,何乐而不为呢?如果觉得有更好更方便的方式,欢迎提出,谢谢。
当UITableView没有数据时,良好的用户体验是关键。通过创建UITableView的Objective-C分类,实现无数据时显示提示,如'暂无数据',避免了代码重复和控制器过度耦合,提高了代码的可维护性。
2649

被折叠的 条评论
为什么被折叠?



