iOS Developer

UITableView_DataSource&Deleg

2016-03-30  本文已影响604人  陈胜华

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

上一篇 下一篇

猜你喜欢

热点阅读