您好,欢迎来到伴沃教育。
搜索
您的当前位置:首页UITableView_DataSource&Deleg

UITableView_DataSource&Deleg

来源:伴沃教育

1.分离目的:为了避免ViewController太重,把TableView的DataSource和Delegate分离出来

Controller文件

//ViewController.m文件
@interface ViewController (){
    TableViewDataSource *dataSource;
    TableViewDelegate   *delegate;
}
@property (strong,nonatomic) UITableView *tableView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    dataSource = [[TableViewDataSource alloc]init];
    delegate   = [[TableViewDelegate alloc]init];
    dataSource.arrList = @[@"1",@"1",@"1",@"1",@"1",@"1"];
    delegate.arrList   = @[@"1",@"1",@"1",@"1",@"1",@"1"];
    
    self.tableView = ({
        UITableView *ettbl = [[UITableView alloc]initWithFrame:CGRectMake(0, 20, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)-20) style:UITableViewStylePlain];
        [ettbl registerClass:[TableViewCell class] forCellReuseIdentifier:@"TableViewCell"];
        ettbl.dataSource   = dataSource;
        ettbl.delegate     = delegate;
        [self.view addSubview:ettbl];
        ettbl;
    });
}

TableViewDataSource&& TableViewDelegate TableViewProtocol文件

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
******************************.h文件**********************************
//TableView代理操作
@interface TableViewDelegate : NSObject<UITableViewDelegate>

@property (nonatomic,strong) NSArray *arrList;

@end

//TableView数据源
@interface TableViewDataSource : NSObject<UITableViewDataSource>

@property (nonatomic,strong) NSArray *arrList;

@end
******************************.m文件**********************************
#import "TableViewDataSource.h"
#import "TableViewCell.h"

@implementation TableViewDelegate

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

@end

@implementation TableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _arrList.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCell"];
    cell.textLabel.text = [NSString stringWithFormat:@"%@",@(indexPath.row)];
    return cell;
}

@end

Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务