viewcontroller瘦身之一(转载)

在一个IOS项目中,viewcontroller通常是最大的文件,并且包含了许多不必要的代码,重用率是最低的。

我们可以尝试给viewcontroller瘦身,让他看起来不是那么的臃肿。

今天说到的是,UITableViewDataSource。

UITableview可能是平时写项目中用到的最多的组件了,使用它要实现它的代理协议和数据源方法,每次都是那么些东西方法controller中,看起来不舒服,我们可以给他瘦身一下。比如这样做。

因为datasource基本上是围绕数组去做一些事,更针对的说就是围绕viewcontroller的数据数组作一些事情,我们可以把它抽出来,单独的放在一个类中,我们使用一个block来设置cell,也可以使用delegate来做这件事,这完全取决于你。

下面上代码,举个栗子~

 1 //
 2 //  ArrayDataSource.h
 3 //  LrdBasicFramework
 4 //
 5 //  Created by 键盘上的舞者 on 5/21/16.
 6 //  Copyright © 2016 键盘上的舞者. All rights reserved.
 7 //  封装的一个dataSource类,可以使controller更加的轻量级
 8  
 9 #import <Foundation/Foundation.h>
10  
11 typedef void(^TableViewCellConfigureBlock)(id cell, id item);
12  
13 @interface ArrayDataSource : NSObject <UITableViewDataSource>
14  
15 - (id)initWithItems:(NSArray *)items
16      cellIdentifier:(NSString *)identifier
17      configureBlock:(TableViewCellConfigureBlock)configureBlock;
18  
19 - (id)itemAtIndexPath:(NSIndexPath *)indexPath;
20  
21 @end
 1 //
 2 //  ArrayDataSource.m
 3 //  LrdBasicFramework
 4 //
 5 //  Created by 键盘上的舞者 on 5/21/16.
 6 //  Copyright © 2016 键盘上的舞者. All rights reserved.
 7 //
 8  
 9 #import "ArrayDataSource.h"
10  
11 @interface ArrayDataSource ()
12  
13 @property (nonatomic, strong) NSArray *items;
14 @property (nonatomic, copy) NSString *identifier;
15 @property (nonatomic, copy) TableViewCellConfigureBlock configureBlock;
16  
17 @end
18  
19 @implementation ArrayDataSource
20  
21 - (instancetype)init {
22     return nil;
23 }
24  
25 - (id)initWithItems:(NSArray *)items cellIdentifier:(NSString *)identifier configureBlock:(TableViewCellConfigureBlock)configureBlock {
26     self = [super init];
27     if (self) {
28         self.items = items;
29         self.identifier = identifier;
30         self.configureBlock = configureBlock;
31     }
32     return self;
33 }
34  
35 - (id)itemAtIndexPath:(NSIndexPath *)indexPath {
36     return self.items[(NSUInteger) indexPath.row];
37 }
38  
39 #pragma mark - DataSource
40 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
41     return self.items.count;
42 }
43  
44 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
45     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.identifier forIndexPath:indexPath];
46     id item = [self itemAtIndexPath:indexPath];
47     self.configureBlock(cell, item);
48     return cell;
49 }
50 @end

然后我们可以在viewcontroller中来这样使用它

posted @ 2016-05-28 11:25  繁星净土  阅读(262)  评论(0)    收藏  举报