【问题标题】:Get current pinned section of UITableView获取 UITableView 的当前固定部分
【发布时间】:2012-03-21 07:11:04
【问题描述】:

获取 UITableView 中最顶部部分的标题或索引的最准确方法是什么?我不是指索引 0 处的部分,而是当前在滚动时固定在顶部的部分标题。

【问题讨论】:

    标签: ios5 uitableview


    【解决方案1】:

    您可以像这样获取屏幕顶部的部分:

         NSUInteger sectionNumber = [[tableView indexPathForCell:[[tableView visibleCells] objectAtIndex:0]] section];
    

    但是,这种方法对你来说可能不是最优的,因为当它处于两个标题之间的过渡期时,它会得到一个奇怪的数字。只要您在过渡期间不需要知道该部分,就可以了。 我希望这就是你要找的,

    【讨论】:

    • 我应该用什么方法来保持 sectionNumber 最新?
    • Scrollviewdidscroll 如果您希望它在每次用户滚动时更新
    • 你必须在访问它的第零个元素之前检查[tableView visibleCells].count > 0
    【解决方案2】:

    我认为与其查询 visibleCells,不如通过以下方式查询索引路径:

    NSInteger section = [[[self.tableView indexPathsForVisibleRows] firstObject] section];
    

    您可以根据需要在UIScrollViewDelegate 方法之一中使用此代码。

    【讨论】:

      【解决方案3】:

      Swift 版本

      使用first(当前固定)或last(最后显示)

        if let section:Int = tableView.indexPathsForVisibleRows?.last?.section {
      
            tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: section), atScrollPosition: UITableViewScrollPosition.None, animated: true)
      
        }
      

      【讨论】:

        【解决方案4】:

        让您的类实现 UIScrollViewDelegate,并实现以下功能。 它将确保您仅在 tableview 停止滚动时检索部分。

        - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
        {
            if (!decelerate)
        {
                // retrieve section here
                section = [[[self.tableview visibleCells] objectAtIndex:0] section];
            }
        }
        
        - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
        {
                // retrieve section here
                section = [[[self.tableview visibleCells] objectAtIndex:0] section];
        }
        

        【讨论】:

        • 我想通过这样做,它可以防止部分在过渡时混淆的问题?
        • 由于某种原因,这会在我的自定义单元格中引发错误...`-[AppointmentCustomCell 部分]:无法识别的选择器已发送到实例 0x89af850`。我所做的就是对您提供的上述代码中的部分进行 NSLogging。
        • 这是旧的但各种错误,因为self.tableView visibleCells 给出了UITableViewCells 而不是IndexPaths。得到 indexPaths 后,我们就可以做 indexPaths[0].section.
        猜你喜欢
        • 2013-07-09
        • 1970-01-01
        • 2020-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多