UITableView,如其义,多用于以表格的形式展示数据。基本用法如下:
1、创建
self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 460) style:UITableViewStyleGrouped];
2、常见属性设置
self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
self.tableView.separatorColor = [UIColor redColor];
self.tableView.backgroundColor = [UIColor orangeColor];
3、设置delegate及datasource
self.tableView.delegate = self;
self.tableView.dataSource = self;
4、实现dataSource和delegate的方法
//必须实现的3个dataSource方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"txTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
return cell;
}
//设置tableView的tableViewCell的高度
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 40.0f;
}
//设置每个section的header的高度
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 50.0f;
}
- (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 50.0f;
}
- (void) tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIAlertView *alertViewSelect = [[UIAlertView alloc]initWithTitle:[NSString stringWithFormat:@"您已选中了%d行",indexPath.row] message:@"您已选中了" delegate:nil cancelButtonTitle:@"取消选中" otherButtonTitles:@"确认选中", nil];
[alertViewSelect show];
}
详细代码可以参照: https://github.com/tingxuan/txUITableViewDemo