首页投稿(暂停使用,暂停投稿)iOS 开发 iOS进阶指南

UIViewController与tableView的dataS

2016-04-01  本文已影响588人  丨n水瓶座菜虫灬

以前当UIViewController有tableView时,经常是UIViewController遵守UITableViewDelegate和UITableViewDataSource,然后在控制器里写要实现的代理方法,以至于很多时候,控制器的代码过多,不利于阅读。为了实现UIViewController与tableView的delegate和dataSource分离开来,今天做了一些小小的尝试,发现是下面的方法是可行的.

#import <Foundation/Foundation.h>
#import <UIKit/UIkit.h> typedef void (^SelectCell)(NSIndexPath *indexPath) typedef void (^ConfigCell)(UITableViewCell *cell, NSIndexPath *indexPath) @interface TableViewDelegateObj : NSObject<UITableViewDelegate, UITableViewDataSource>
+ (instancetype)createTableViewDelegateObjWithDataList:(NSMutableArray *)dataList configCellBlock:(ConfigCell)configCellBlock selectCellBlock:(SelectCell)selectCellBlock; @end

#import "TableViewDelegateObj"
@imterface TableViewDelegateObj() @property (nonatomic, strong) NSMutableArray *dataList; @property (nonatomic, copy) SelectCell selectCellBlock; @property (nonatomic, copy) ConfigCell configCellBlock; @end
@implementation TableViewDelegateObj
- (instancetype)initWithDataList:(NSMutableArray *)dataList configCellBlock:(ConfigCell)configCellBlock selectCellBlock:(SelectCell)selectCellBlock { self = [super init]; if (!self) { return nil; } self.dataList = dataList; self.configCellBlock = configCellBlock; self.selectCellBlock = selectCellBlock; }
`+ (instancetype)createTableViewDelegateObjWithDataList:(NSMutableArray *)dataList configCellBlock:(ConfigCell)configCellBlock selectCellBlock:(SelectCell)selectCellBlock {
TableViewDelegateObj *obj = [[self alloc] initWithDataList:dataList configCellBlock:configCellBlock selectCellBlock:selectCellBlock];

return obj;
}- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.dataList.count;
}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
self.configCellBlock(cell, indexPath);
return cell
}- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
self.selectCellBlock(indexPath)
}`

上一篇 下一篇

猜你喜欢

热点阅读