ios - 在代码中使用静态单元格重新排序 UITableview

标签 ios objective-c uitableview

我有一个带有 7 个静态单元格的 UITableview,每个单元格都有一个到另一个 View 的 segue。我想让 Cells 可以重新排序。
在用户重新排序单元后,我将每个单元的重用 ID 和位置写入 NSUserdefaults。

但是,当 View (重新)加载时,我如何告诉 Tableview 需要在哪里显示单元格。

最好的祝福

短剑

最佳答案

通常,当使用静态 TableView 时,您不会实现数据源方法,但在这种情况下似乎有必要这样做。我创建了一个 IBOutletCollection,并将我的单元格添加到该数组中(我按从第一个单元格到最后一个单元格的顺序添加它们,因此它们会在第一次加载表格时出现在 Storyboard 中)。在 cellForRowAtIndexPath 中,您不能使单元格出队,因为这不适用于静态单元格,因此,我从 socket 集合中获取单元格。我有一个单独的数组来跟踪单元格应该出现的顺序,这就是我保存到用户默认值的内容。这是在我的测试中有效的代码,

@interface StaticTableViewController ()
@property (strong,nonatomic) NSMutableArray *cells;
@property (strong, nonatomic) IBOutletCollection(UITableViewCell) NSArray *tableCells;

@end

@implementation StaticTableViewController

-(void)viewDidLoad {
    [super viewDidLoad];
    self.cells = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"cells"] mutableCopy];
    if (! self.cells) self.cells = [@[@0,@1,@2,@3,@4] mutableCopy];
}



- (IBAction)enableReordering:(UIBarButtonItem *)sender {
    [self.tableView setEditing:YES animated:YES];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.cells.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger idx = [self.cells[indexPath.row] integerValue];
    UITableViewCell *cell = self.tableCells[idx];
    return cell;
}



-(BOOL)tableView:(UITableView *)tableview shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}


-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleNone;
}


- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
    NSNumber *numberToMove = self.cells[fromIndexPath.row];
    [self.cells removeObjectAtIndex:fromIndexPath.row];
    [self.cells insertObject:numberToMove atIndex:toIndexPath.row];
    [[NSUserDefaults standardUserDefaults] setObject:self.cells forKey:@"cells"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

关于ios - 在代码中使用静态单元格重新排序 UITableview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24245004/

相关文章:

ios - 删除单元格时表头 View 向左滑动

ios - 我无法让类别出现在表格 View 单元格中

ios - 单行 UITableView 在滚动之前不显示 detailTextLabel

ios - 在 Swift 中使用动画将按钮从一个 UITableViewCell 移动到另一个

iphone - 从 View Controller 中删除顶部栏

ios - 在 iOS 上升级到 Opencv 2.4.5 后出现编译器错误。是否有快速解决这些问题的方法?

objective-c - C函数访问Objective-C类的私有(private)ivar

ios - swift 中的自定义 Collection View 单元格

iphone - 核心数据 - 对作为关系的一部分获取的记录进行排序

ios - Objective-C 将导航栏添加到 rootview