DSDataSource.m
2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//
// DSDataSource.m
// DreamSleep
//
// Created by peter on 2022/4/8.
//
#import "DSDataSource.h"
@interface DSDataSource ()
/** 是否是section */
@property NSInteger isSection;
@end
@implementation DSDataSource
- (id)initWithIdentifier:(NSString *)identifier datas:(NSArray *)datas isSection:(BOOL)isSection configureBlock:(CellConfigureBlock)cellBlock {
if (self = [super init]) {
_cellIdentifier = identifier;
_dataArray = [NSMutableArray arrayWithArray:datas];
_isSection = isSection;
_cellConfigureBlock = [cellBlock copy];
}
return self;
}
- (void)addDataArray:(NSArray *)datas {
if(!datas) { return; }
if (self.dataArray.count > 0) { [self.dataArray removeAllObjects]; }
[self.dataArray addObjectsFromArray:datas];
}
- (id)modelAtIndexPath:(NSIndexPath *)indexPath {
// 需要判断是否是row还是section
if (self.isSection) {
return self.dataArray.count > indexPath.section ? self.dataArray[indexPath.section] : nil;
} else {
return self.dataArray.count > indexPath.row ? self.dataArray[indexPath.row] : nil;
}
}
#pragma mark - UITableViewDataSource
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
UITableViewCell *cell = self.cellIdentifier ? [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath] :
[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
id model = [self modelAtIndexPath:indexPath];
if (self.cellConfigureBlock) {
self.cellConfigureBlock(cell, model, indexPath);
}
return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (self.isSection) {
return !self.dataArray ? 1 : self.dataArray.count;
} else {
return 1;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (self.isSection) {
return 1;
} else {
return !self.dataArray ? 1 : self.dataArray.count;
}
}
@end