// 创建一个UITableView的步骤
#import "ViewController.h"
// 第一步:遵守两个UITableView的代理协议
@interface ViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@end
- (void)viewDidLoad {
[super viewDidLoad];
self.dataArray = [[NSMutableArray alloc] initWithObjects:@"胡凯", @"吕世涛", nil];
// 第二步:初始化UITableView,并指定大小和样式
self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
// 第三步:指定UITableView的两个代理方法的代理人
self.tableView.delegate = self;
self.tableView.dataSource = self;
// 第四步:添加到self.view 上
[self.view addSubview:self.tableView];
}
// 第五步:返回 有多少个cell
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// 一般情况下 返回一个数组的count
return self.dataArray.count;
}
// 第六步:返回每个cell的样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//返回cell的步骤:
// 第一步:在静态区初始化一个字符串,作为重用池的标识符
// 因为每次使用cell的时候 都会走这个方法,如果不放在静态区就会大量的初始化字符串
static NSString *str = @"CELL";
// 第二步:初始化一个cell,并从重用池里面 拿到这个cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
// 第三步:判断cell是否存在,如果不存在 则创建一个cell
if (!cell) {
// 创建的时候,指定cell的样式,并告诉cell 应该进入哪个重用池
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str];
}
// 第四步:给cell赋值
cell.textLabel.text = self.dataArray[indexPath.row];
// 第五步:返回cell
return cell;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
下面这个是高级写法
#import "ViewController.h"
@interface ViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.dataArray = [[NSMutableArray alloc] initWithObjects:@"胡凯", @"吕世涛", nil];
self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
self.tableView.delegate = self;
self.tableView.dataSource = self;
[_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CELL"];
[self.view addSubview:self.tableView];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
return cell;
}
@end
学习的一些小总结。如有问题希望大神指教!谢谢