UITableView没数据时用户提示该怎么做?

来源:互联网 发布:荷兰国旗算法 编辑:程序博客网 时间:2024/05/11 11:03

前言

我们都知道几乎所有的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;}

效果图:
这里写图片描述

总结

只要你用得到的地方,导入这个分类就可以使用,是不是很方便呢,也不需要写重复代码,还易于维护,何乐而不为呢?如果觉得有更好更方便的方式,欢迎提出,谢谢。

0 0
原创粉丝点击