【问题标题】:Determine visible sections of a UITableView when sections have no rows当部分没有行时确定 UITableView 的可见部分
【发布时间】:2014-04-04 20:03:44
【问题描述】:

我正在尝试确定哪些部分当前在我的 UITableView 中可见。但是,有时我的部分没有行,只显示它们的部分标题。有没有办法确定,也许通过使用部分标题,我的 UITableView 中的哪些部分当前正在显示?要求 -(NSArray *)indexPathsForVisibleRows 无法确定节,因为没有可见的实际行,只有节标题。

【问题讨论】:

    标签: ios objective-c uitableview


    【解决方案1】:

    我能想到的最好办法是使用 contentOffset 和 frame.size 来计算可见矩形并遍历每个调用 rectForSection: 的部分,然后查看哪些相交。比如:

    -(NSIndexSet*)visibleSections
    {
        NSMutableIndexSet*  indexSet = [NSMutableIndexSet new];
        CGRect              visible = self.tableView.bounds;
    
        for(NSInteger section = 0 ; section < [self numberOfSections])
        {
            CGRect          sectBounds = [self.tableView rectForSection:section];
    
            if(CGRectIntersectsRect(sectBounds, visible))
            {
                [indexSet addIndex:section];
            }
        }
    
        return indexSet;
    }
    

    【讨论】:

    • 这很好用!我所做的唯一调整是使用 self.tableview.bounds 而不是获取框架并修改它的原点。
    • 是的,这可能是更好的主意:)
    【解决方案2】:

    斯威夫特版本

    if let visibleRows = tableView.indexPathsForVisibleRows {
        let visibleSections = visibleRows.map({$0.section})
    }
    

    【讨论】:

    • 这不适用于可展开的可折叠部分
    【解决方案3】:

    Swift 3 版本 od @David 回答

    func visibleSection() -> IndexSet {
    
            var indexSet: IndexSet = IndexSet()
            let visibleRect: CGRect = self.bounds
    
            for sectionIndex in 0..<self.numberOfSections {
    
                let sectionBounds = self.rect(forSection: sectionIndex)
    
                if sectionBounds.intersects(visibleRect) {
    
                    indexSet.insert(sectionIndex)
                }
            }
            return indexSet
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2012-03-26
      • 2016-08-14
      • 1970-01-01
      • 2012-03-21
      • 2010-12-20
      相关资源
      最近更新 更多