前些天遇到這樣一個需求,點擊cell的按鈕 需要上下移動該cell.在這里記錄一下 方便以后查閱.
效果是這樣的:
下面列出完成這個需求的過程 所注意的點:
1.實現(xiàn)點擊頂部按鈕、底部按鈕的action
W_S
cell.upTapBlock = ^(UIButton *sender) {
if (indexPath.row == 0) {
return ;
}
//sourceIndexPath是被點擊cell的IndexPath
NSIndexPath *sourceIndexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:0];
NSIndexPath *destinationIndexPath = [NSIndexPath indexPathForRow:indexPath.row - 1 inSection:0];
[self.discussMutableMsgs exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
//移動cell的位置
[weakSelf.previewTable moveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
[weakSelf.previewTable reloadRowsAtIndexPaths:@[sourceIndexPath,destinationIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
};
cell.downTapBlock = ^(UIButton *sender) {
if (indexPath.row == self.discussMutableMsgs.count - 1) {
return ;
}
//sourceIndexPath是被點擊cell的IndexPath
NSIndexPath *sourceIndexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:0];
NSIndexPath *destinationIndexPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:0];
[self.discussMutableMsgs exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
//移動cell的位置
[weakSelf.previewTable moveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
[weakSelf.previewTable reloadRowsAtIndexPaths:@[sourceIndexPath,destinationIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
};
2.注意通知系統(tǒng)哪些行可以移動
-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
return YES;
}
還需要注意的是 cell 復(fù)用會造成bug,于是在給cell 綁定數(shù)據(jù)的時候
[self.contentView removeAllSubviews];