NBReorderTableView 是一个 UITableView
子类,用于支持长按重新排列单元格。它正在产品上使用,用于 --Listary-- 和 Todoist for iOS
只需使用一个 NBReorderTableView
表视图。
UITableView *tableView = [NBReorderTableView new];
至少实现 tableView:placeholderViewForReorderingCell:
代理方法来返回正在重新排列的单元格的视图表示。有关更多有趣的代理方法,请参阅 NBReorderTableView.h
。
- (UIView *)tableView:(UITableView *)tableView placeholderViewForReorderingCell:(UITableViewCell *)cell
{
// Create an image from the cell being dragged
UIGraphicsBeginImageContextWithOptions(cell.contentView.bounds.size, NO, 0);
[cell.contentView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *cellImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Create the placeholder view to be dragged
UIImageView *placeholder = [[UIImageView alloc] initWithImage:cellImage];
// Set the view's frame
CGRect frame = placeholder.frame;
frame.origin.y = cell.frame.origin.y;
placeholder.frame = frame;
placeholder.layer.shouldRasterize = YES;
placeholder.layer.shadowOpacity = 0.4;
placeholder.layer.shadowRadius = 2;
placeholder.layer.shadowOffset = CGSizeZero;
placeholder.layer.zPosition = MAXFLOAT;
[UIView animateWithDuration:0.25 animations:^{
placeholder.transform = CGAffineTransformMakeScale(1.02, 1.02);
}];
placeholder.alpha = 0.8;
return placeholder;
}
最后,实现 tableView:moveRowAtIndexPath:toIndexPath:
数据源方法来更新用户重新排列单元格时的数据源。
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
[self.rows exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
}
Nuno Baldaia, http://nunobaldaia.com
NBReorderTableView 在 MIT 许可协议下可用。有关更多信息,请参阅 LICENSE 文件。