美文网首页iOS收藏
iOS 自定义tableView代理方法

iOS 自定义tableView代理方法

作者: iOS_肖晨 | 来源:发表于2017-10-18 10:32 被阅读24次

在使用MVC架构模式书写代码的过程中,难免会遇到大量的代理方法写在控制器(C)里面,使得控制器代码异常庞大并且不便于阅读。
这种情况下可以选择将一部分代理方法代码抽到代理类里面,从而达到一定程度的优化。

如下是实现步骤代码:
  1. 实现一个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. 在控制器中创建TableViewModel类的属性,防止调用一次之后被销毁
@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];
}
实现截图:

相关文章

网友评论

    本文标题:iOS 自定义tableView代理方法

    本文链接:https://www.haomeiwen.com/subject/spesuxtx.html