iOS 自定義tableView代理方法

在使用MVC架構(gòu)模式書寫代碼的過程中,難免會遇到大量的代理方法寫在控制器(C)里面,使得控制器代碼異常龐大并且不便于閱讀。
這種情況下可以選擇將一部分代理方法代碼抽到代理類里面,從而達到一定程度的優(yōu)化。

如下是實現(xiàn)步驟代碼:
  1. 實現(xiàn)一個TableViewModel代理類

TableViewModel.h

@interface TableViewModel : NSObject <UITableViewDataSource, UITableViewDelegate>

@property (assign, nonatomic) NSInteger row;
- (void)initModelWithTableView:(UITableView *)tableView;

@end

TableViewModel.m


- (void)initModelWithTableView:(UITableView *)tableView {
    tableView.delegate = self;
    tableView.dataSource = self;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return (self.row > 0) ? self.row : 8;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 20;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"cellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"section -- %ld, row -- %ld", indexPath.section, indexPath.row];
    cell.textLabel.textColor = [UIColor blueColor];
    cell.backgroundColor = [UIColor lightGrayColor];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"didSelectRow -- %ld", indexPath.row);
}

@end
  1. 在控制器中創(chuàng)建TableViewModel類的屬性,防止調(diào)用一次之后被銷毀
@interface ViewController3 ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) TableViewModel *model;

@end
  1. 初始化TableViewModel類并將設置好的TableView傳遞過去。
    row屬性僅僅為了舉例說明,使用時可以選擇通過多屬性或block的方式將所需的值傳遞過去。
- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"tableView" owner:self options:nil];
    _tableView = [views lastObject];
    [self.view addSubview:_tableView];
    
    _model = [[TableViewModel alloc] init];
    _model.row = 12;
    [_model initModelWithTableView:_tableView];
}
實現(xiàn)截圖:
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容