2013-06-11 38 views
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]; 
} 
+0

那么究竟是什么不告诉你的代码工作?你有没有崩溃?我看到的唯一问题是,你从不在'cellForRowAtIndexPath'中创建一个单元格。当您从表视图出列单元格,你应该说'如果(细胞!){电池= [[[UITableViewCell的页头]初始化...]自动释放]; }' – herzbube

+0

我需要保存单元格的顺序。我不知道该怎么做。一切运行良好。 –

+0

我不认为我理解。表格视图单元格是'maTheData'中数据的可视化表示。插入新单元格或删除或移动现有单元格时,可以很好地更新'maTheData'以反映GUI中的更改。因此,单元格的顺序由'maTheData'中的元素顺序反映。那么你还想要什么? – herzbube

回答

-2

为了保持跨应用程序重新发布的数据,你必须的maTheData内容序列化到NSData,然后要么通过NSUserDefaults写的NSData到磁盘的内容,或您自己选择的文件。在后一种情况下,你还必须决定在哪个文件夹要放置该文件 - 我建议类似的应用程序支持文件夹,或者无论如何,文档文件夹。

我知道这是不是复制粘贴&的解决方案,但它应该让你开始你的进一步研究。只要阅读苹果文档和谷歌,网络上有很多资源可以解释如何做到这一点。