【发布时间】:2014-04-04 20:03:44
【问题描述】:
我正在尝试确定哪些部分当前在我的 UITableView 中可见。但是,有时我的部分没有行,只显示它们的部分标题。有没有办法确定,也许通过使用部分标题,我的 UITableView 中的哪些部分当前正在显示?要求 -(NSArray *)indexPathsForVisibleRows 无法确定节,因为没有可见的实际行,只有节标题。
【问题讨论】:
标签: ios objective-c uitableview
我正在尝试确定哪些部分当前在我的 UITableView 中可见。但是,有时我的部分没有行,只显示它们的部分标题。有没有办法确定,也许通过使用部分标题,我的 UITableView 中的哪些部分当前正在显示?要求 -(NSArray *)indexPathsForVisibleRows 无法确定节,因为没有可见的实际行,只有节标题。
【问题讨论】:
标签: ios objective-c uitableview
我能想到的最好办法是使用 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;
}
【讨论】:
斯威夫特版本
if let visibleRows = tableView.indexPathsForVisibleRows {
let visibleSections = visibleRows.map({$0.section})
}
【讨论】:
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
}
【讨论】: