首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将UITableView行重排序限制为一个节

如何将UITableView行重排序限制为一个节
EN

Stack Overflow用户
提问于 2009-05-11 20:27:58
回答 4查看 32.2K关注 0票数 123

我在这个问题上撞到了头,谷歌却什么也没找到。我最终解决了它,并认为我应该把它写在这里,为了下一个人。

您有一个包含多个部分的UITableView。每个部分都是同构的,但表整体上是不同的。因此,您可能希望允许在一个区段内重新排序行,但不允许跨区段重新排序。也许你甚至只想要一个部分是可重新排序的(这就是我的情况)。如果您像我一样查看UITableViewDataSourceDelegate,您不会发现它何时允许您在节之间移动行的通知。当它开始移动一行时,你会得到一个(这很好),当它已经移动它时,你会得到一个,并且你有机会与你的内部数据同步。没什么用。

那么如何防止不同部分之间的重新排序呢?

我会将我所做的作为单独的答案发布,让其他人发布更好的答案!

EN

回答 4

Stack Overflow用户

发布于 2009-05-11 20:51:38

此实现将防止在原始节之外进行重新排序(如Phil的回答),但它也会将记录捕捉到节的第一行或最后一行,这取决于拖动的位置,而不是开始的位置。

代码语言:javascript
复制
- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{
  if (sourceIndexPath.section != proposedDestinationIndexPath.section) {
    NSInteger row = 0;
    if (sourceIndexPath.section < proposedDestinationIndexPath.section) {
      row = [tableView numberOfRowsInSection:sourceIndexPath.section] - 1;
    }
    return [NSIndexPath indexPathForRow:row inSection:sourceIndexPath.section];     
  }

  return proposedDestinationIndexPath;
}
票数 183
EN

Stack Overflow用户

发布于 2009-05-11 20:34:16

很简单,真的。

UITableViewDelegate有这样的方法:

代码语言:javascript
复制
tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath:

当用户将鼠标悬停在可能的下拉点上时,将调用此函数。你有机会说,“不!不要把它扔在那里!把它扔到这里来。”您可以将不同的索引路径返回到建议的索引路径。

我所做的就是检查部分索引是否匹配。如果它们这样做了,那么很好,返回建议的路径。如果不是,则返回源路径。这也很好地防止了其他部分中的行甚至在您拖动时移动-并且当您尝试将其移动到另一个部分时,被拖动的行将捕捉回其原始位置。

代码语言:javascript
复制
- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{
    if( sourceIndexPath.section != proposedDestinationIndexPath.section )
    {
        return sourceIndexPath;
    }
    else
    {
        return proposedDestinationIndexPath;
    }
}
票数 77
EN

Stack Overflow用户

发布于 2014-07-27 08:20:31

您可以使用下面的方法防止在节间移动行。只是不允许在两节之间有任何移动。您甚至可以控制某一节中特定行的移动。例如,节中的最后一行。

示例如下:

代码语言:javascript
复制
- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath {

    // Do not allow any movement between section
    if ( sourceIndexPath.section != proposedDestinationIndexPath.section) {
        return sourceIndexPath;
    }
    // You can even control the movement of specific row within a section. e.g last row in a     Section

    // Check if we have selected the last row in section
    if (sourceIndexPath.row < sourceIndexPath.length) {
        return proposedDestinationIndexPath;
    } 
    else {
        return sourceIndexPath;
    }
}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/849926

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档