0
我有一个可以重新排列UITableViewCells的顺序,可以删除细胞然而一个应用程序,我needa方法来保存重新排列或删除表格视图单元的顺序。我使用一个NSMutableArray保存细胞重新排列的顺序表视图
- (void)viewDidLoad
{
[super viewDidLoad];
if (!maTheData) {
maTheData = [[NSMutableArray alloc] initWithObjects:@"Bus", @"Truck", @"Car",nil];
}
}
- (NSInteger)numberOfSectionsInTableView: (UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [maTheData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tvcItems"];
UILabel *lblName = (UILabel *)[cell viewWithTag:100];
[lblName setText:[maTheData objectAtIndex: [indexPath row]]];
return cell;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[maTheData removeObjectAtIndex:[indexPath row]];
// Delete row using the cool literal version of [NSArray arrayWithObject:indexPath]
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Insert something into the array, and you can just add a populated NSIndexPath of data or simplr reload data
[maTheData addObject:@"I'm a new item!"];
[tableView reloadData];
}
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
NSString *mover = [maTheData objectAtIndex: [fromIndexPath row]];
[maTheData removeObjectAtIndex:[fromIndexPath row]];
[maTheData insertObject:mover atIndex:[toIndexPath row]];
[tableView setEditing:NO animated:YES];
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView setEditing:YES animated:YES];
}
那么究竟是什么不告诉你的代码工作?你有没有崩溃?我看到的唯一问题是,你从不在'cellForRowAtIndexPath'中创建一个单元格。当您从表视图出列单元格,你应该说'如果(细胞!){电池= [[[UITableViewCell的页头]初始化...]自动释放]; }' – herzbube
我需要保存单元格的顺序。我不知道该怎么做。一切运行良好。 –
我不认为我理解。表格视图单元格是'maTheData'中数据的可视化表示。插入新单元格或删除或移动现有单元格时,可以很好地更新'maTheData'以反映GUI中的更改。因此,单元格的顺序由'maTheData'中的元素顺序反映。那么你还想要什么? – herzbube