IOS 表视图(UITableVIew)的使用方法(6)表视图的编辑功能(新增Add)

时间:2023-03-09 13:34:01
IOS 表视图(UITableVIew)的使用方法(6)表视图的编辑功能(新增Add)

表视图的新增功能和删除功能虽然目的不同,但是工作流程是相似的

下面列出在处理新增的回调函数时,与删除所不同的逻辑部分代码。

显示下过如下:IOS 表视图(UITableVIew)的使用方法(6)表视图的编辑功能(新增Add)

#pragma mark
#pragma mark Table View data source
//setEditing:animated:后被调用
//询问具体Cell是不是支持编辑
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
} -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSMutableArray *arrNewDatasource=[NSMutableArray arrayWithArray:self.datasource]; //cell新增处理
if(editingStyle == UITableViewCellEditingStyleInsert)
{
//新建一个HBPlayer对象
HBPlayerInfo *newPlayer=[[HBPlayerInfo alloc]init];
newPlayer.name=@"My Player";
newPlayer.role=@"GoalKeeper";
newPlayer.number=@""; //插入
[arrNewDatasource insertObject:newPlayer atIndex:indexPath.row]; //更新datasource
_datasource = [[NSArray alloc]initWithArray:arrNewDatasource]; //更新界面
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
} -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"InfoTableViewCellId";
HBCustomCell *cell =(HBCustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if(cell == nil)
{
NSArray *arrNib=[[NSBundle mainBundle]loadNibNamed:@"CustomView" owner:self options:nil];
if(arrNib)
{
//第一个元素就是需要的UITableViewCell
cell=(HBCustomCell *)[arrNib objectAtIndex:];
}
} UIImage *photo = nil;
HBPlayerInfo *onePlayer=[self.datasource objectAtIndex:indexPath.row];
if(onePlayer)
{
cell.playerName.text=onePlayer.name;
cell.playerName.font=[UIFont fontWithName:@"Helvetica" size:16.0f];
cell.playerRole.text=onePlayer.role;
cell.playerRole.font=[UIFont fontWithName:@"Helvetica" size:12.0f];
cell.playerNumber.text=[NSString stringWithFormat:@"No.%@",onePlayer.number]; //插入时,更新界面的方法insertRowsAtIndexPaths会调用cellForRowAtIndexPath询问具体的UITableViewCell
//所以这里考虑为插入的元素准备的空头像
photo=[UIImage imageNamed:@"gaolin.jpeg"];
if(!photo)
{
photo=[UIImage imageNamed:@"empty"];
}
cell.playerPhoto.image=photo;
}
return cell;
} #pragma mark
#pragma mark TableView Delegate
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleInsert; /*
//只有编辑状态时,才有删除功能
//由于手指左划显示“Delete”按钮并不处于编辑状态,所以会被屏蔽掉
if(self.tableView.editing)
{
return UITableViewCellEditingStyleDelete;
}
return UITableViewCellEditingStyleNone;
*/
}