UITableView的使用
// UITableView 的使用
UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 480) style:UITableViewStylePlain];
// 分割线颜色
tableView.separatorColor = [UIColor redColor];
// 背景颜色
tableView.backgroundColor = [UIColor yellowColor];
// 集中调整每行高度 默认高度44
tableView.rowHeight = 60;
[self.view addSubview:tableView];
[tableView release];
指定代理
// 指定tableView的代理人
// delegate 都是响应View的各种状态
tableView.delegate = self;
// dataSource的协议方法 都是给tableView提供数据的
tableView.dataSource = self;
tableView协议方法(必须实现)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// 告诉tableView 每个section要显示多少行
// 根据数组的元素个数确定行数
return [self.array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// TableViewCell的重用机制
// 1,尝试从重用池中获取一个cell
static NSString *identifier = @"reuse";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
// 2,判断cell是否获取到
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier] autorelease];
}
// 从数组取值
NSString *name = self.array[indexPath.row];
// cell自带一个imageView 和两个label
cell.textLabel.text = name;
cell.detailTextLabel.text = @"2222";
return cell;
}
tableView的分区协议
#pragma mark - tableView分区的协议方法
// 有多少个分区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// 默认返回值为1
return 3;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
// 设置分区顶部的标题
return [NSString stringWithFormat:@"第%d区", section];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
// 分区顶部的高度 默认20
return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 设置每一行的高度
if (indexPath.row == 0) {
return 100;
} else {
return 50;
}
}
tableView选择和取消选择
#pragma mark - tableView的协议方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"选中的行数: %d", indexPath.row);
NSString *name = [self.array objectAtIndex:indexPath.row];
NSLog(@"选中了: %@", name);
}
//取消选中的方法 一般不用
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
//取消选中的方法
}