swiftiOS Developer好东西

iOS UITableView展示无数据界面(基于KVO)

2017-04-16  本文已影响169人  calary

1.前言

在UITableView(或UICollectionView)无数据时我们希望展示一个无数据页面(图片或文字,还有可能加个按钮),而不是空空的什么都没有,最终我们的展示效果如下图:

屏幕快照 2017-04-15 下午11.19.19.png

2.思路

3.实现(主要代码)

//.h文件
#import <UIKit/UIKit.h>

@interface BaseTableView : UITableView

//无数据时的高度,默认20(因为我们有可能会加footerView和headerView,这个时候无数据的高度就不为0了)
//row 的高度一般不会小于30,所以选了个折中的高度20;如果无数据时的高度大于20,可以在初始化后重新设置这个高度
@property (nonatomic, assign) CGFloat noDataHeight;

@end

//.m文件
#import "BaseTableView.h"
#import "FBKVOController.h"

@interface BaseTableView()
@property (nonatomic, strong) FBKVOController *kvoController;
@property (nonatomic, strong) UILabel *stringLabel;

@end

@implementation BaseTableView

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style
{
    self = [super initWithFrame:frame style:style];
    if (self){
        //默认无数据高度
        self.noDataHeight = 20;
        
        [self drawView];
        [self initFBKVO];
    }
    return self;
}

//可以自定义的view,可以添加图片按钮等,这里只是简单的显示个label
- (void)drawView{
    _stringLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 20)];
    _stringLabel.center = self.center;
    _stringLabel.text = @"空空如也~~";
    _stringLabel.hidden = YES;
    _stringLabel.font = [UIFont systemFontOfSize:15];
    _stringLabel.textAlignment = NSTextAlignmentCenter;
    _stringLabel.textColor = [UIColor blackColor];
    [self addSubview:_stringLabel];
}

//关键代码
- (void)initFBKVO{
    
    //KVO
    __weak typeof (self) weakSelf = self;
    self.kvoController = [FBKVOController controllerWithObserver:self];
    [self.kvoController observe:self keyPath:@"contentSize" options:NSKeyValueObservingOptionNew block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSString *,id> * _Nonnull change) {
       // contentSize有了变化即会走这里
        CGFloat height =  weakSelf.contentSize.height;
     //如果高度大于我们规定的无数据时的高度则隐藏无数据界面,否则展示
        if ( height > weakSelf.noDataHeight){
            _stringLabel.hidden = YES;
        }else {
            _stringLabel.hidden = NO;
        }
    }];
}
@end

4.使用示例

#import "BaseTableView.h"
//...
@property (nonatomic, strong) BaseTableView *tableView;

//...
- (void)drawView{
_tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
//如果有必要设置的话
// _tableView.noDataHeight = 30;
}

5.总结

这种实现相对来讲还是很方便的,如果无数据界面有按钮,直接写个代理或者用block即可,可扩展性很强,简单方便,希望可以帮到你,如果对你有所帮助,记得点赞哦。

上一篇 下一篇

猜你喜欢

热点阅读