免费开源的iOS开发学习平台

UITableView详解:15-改变Cell位置

在表视图中的单元格Cell,可以通过代理方法调整其显示的顺序/位置,该功能在实际的应用开发中,使用的并不太广泛,建议广大网友了解相关功能即可。

单元格位置调整相关的属性和方法

如果需要调整Cell的位置,则需要设置表视图的editing属性为YES。

@property (nonatomic, getter=isEditing) BOOL editing;  // 默认为NO

另外,还需要添加tableView:moveRowAtIndexPath:toIndexPath:代理方法,在该方法中,可以获取单元格的原索引位置sourceIndexPath以及更新后的索引位置destinationIndexPath,通过这两个属性,我们需要去修改该单元格对应的数据在数据源数组中的位置,以便再次刷新界面后,该单元格的显示顺序是不变的。

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath;
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    MYModel *model = self.rowDataArray[sourceIndexPath.row];
    [self.rowDataArray removeObjectAtIndex:sourceIndexPath.row];
    [self.rowDataArray insertObject:model atIndex:destinationIndexPath.row];
}

示例代码

https://github.com/99ios/8.2.15