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

本文介绍了两种方法在UITableView没有数据时,展示'暂无数据'的背景提示。方法一利用Objective-C的分类,通过类扩展实现;方法二则是通过继承UITableView并自定义视图来达成目的。

需求:

当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  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值