1. 程式人生 > >OC 建立TableView基類並結合MJRefresh實現上拉重新整理,下拉載入

OC 建立TableView基類並結合MJRefresh實現上拉重新整理,下拉載入

1.建立繼承自UITableView的基類BaseTableView:

#import <UIKit/UIKit.h>
@class BaseTableView;
@protocol BaseTableViewDelegate <NSObject>
@optional
//下拉重新整理
- (void)refresh:(BaseTableView *)tableView;
//上拉載入
- (void)reload:(BaseTableView *)tableView;

@end
@interface BaseTableView : UITableView
//能否重新整理
@property (nonatomic, assign)BOOL enableRefresh;
//能否載入
@property (nonatomic, assign)BOOL enableReloadData;
//是否有資料
@property (nonatomic, assign)BOOL isNoData;
@property (nonatomic, weak)id<BaseTableViewDelegate>EventDelegate;
@property (nonatomic, strong)UILabel *noDataLabel;
@end
#import "BaseTableView.h"

@implementation BaseTableView
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style{
    if ([super initWithFrame:frame style:style]) {
#pragma mark - 重新整理
        self.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            if ([self.EventDelegate respondsToSelector:@selector(refresh:)]) {
                [self.EventDelegate refresh:self];
            }
        }];
#pragma mark - 載入
        self.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            if ([self.EventDelegate respondsToSelector:@selector(reload:)]) {
                [self.EventDelegate reload:self];
            }
        }];
#pragma mark - 有無資料提示
        [self addSubview:self.noDataLabel];
#pragma mark - tableview 設定
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.backgroundColor = [UIColor groupTableViewBackgroundColor];
    }
    return self;
}
#pragma mark - 設定能否重新整理
- (void)setEnableRefresh:(BOOL)enableRefresh {
    _enableRefresh = enableRefresh;
    if (_enableRefresh) {
        self.mj_header.hidden = NO;
    }else {
        self.mj_header.hidden = YES;
    }
}
#pragma mark - 設定能否載入
- (void)setEnableReloadData:(BOOL)enableReloadData {
    _enableReloadData = enableReloadData;
    if (_enableReloadData) {
        self.mj_footer.hidden = NO;
    }else {
        self.mj_footer.hidden = YES;
    }
}
#pragma mark - 設定是否有資料
- (void)setIsNoData:(BOOL)isNoData {
    _isNoData = isNoData;
    if (_isNoData) {
        self.noDataLabel.hidden = NO;
    }else {
        self.noDataLabel.hidden = YES;
    }
}
#pragma mark - 懶載入沒有資料的提示
- (UILabel *)noDataLabel {
    if (!_noDataLabel) {
        _noDataLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, (self.height - 40) / 2 , self.width, 40)];
        _noDataLabel.font = [UIFont systemFontOfSize:17];
        _noDataLabel.textAlignment = NSTextAlignmentCenter;
        _noDataLabel.text = @"暫無資料";
        _noDataLabel.textColor = [UIColor grayColor];
    }
    return _noDataLabel;
}
@end