如果您在保存 UITableView 单元格后重新加载 tableView,那么它将重新排序为初始值,因为您设置单元格数据的数组是原样的。您只能更改表格视图单元格而不是数组中的数组数据位置。
下面我编写了一个 UITableView 代码来移动单元格,它在推送视图后工作正常。如果我从 viewWillAppear中删除 reload 方法:
#import "MoveCellViewController.h"
@interface MoveCellViewController ()
@end
@implementation MoveCellViewController
- (void)viewDidLoad
{
UIBarButtonItem *left=[[UIBarButtonItem alloc] initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(edit)];
self.navigationItem.leftBarButtonItem=left;
myArray=[[NSMutableArray alloc]init]; //mutable array;
myArray=[NSMutableArray arrayWithObjects:@"Aman",@"Ankit",@"Sumit",@"Hercules",@"Jackie Chan", nil];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)edit
{
if (self.navigationItem.leftBarButtonItem.title==@"Edit") {
self.navigationItem.leftBarButtonItem.title=@"Done";
[_tableView setEditing:YES];
}else
{
[_tableView setEditing:NO];
self.navigationItem.leftBarButtonItem.title=@"Edit";
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [myArray count];
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier=@"cellIdentifier";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell==nil) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.userInteractionEnabled=YES;
cell.textLabel.text=[myArray objectAtIndex:indexPath.row];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewCellEditingStyleNone;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
id ob = [myArray objectAtIndex:destinationIndexPath.row];
[myArray replaceObjectAtIndex:destinationIndexPath.row withObject:[myArray objectAtIndex:sourceIndexPath.row]];
[myArray replaceObjectAtIndex:sourceIndexPath.row withObject:ob];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NextViewController *nx=[[NextViewController alloc] init];
[self.navigationController pushViewController:nx animated:YES];
}
@end
这是工作代码,在推送视图控制器后不会更改。