Demo地址(有拓展哟)(PS:今天有点累.明天更新一下博客)
我一开始的思路和这一篇文章差不多.大致思路是通过显示组头.将要显示组头的UITableView代理方法来判断最上层是哪个组头.思路是没有错误的,但是试玩了一下.在两个组切换之间.不松手的上下滑动会有BUG(具体表现为当前显示组头一直+1,+1,+1).
{
//使用currentTopSectionViewCount记录当前显示的最上层的Section.在控制器中初始化为0.
long _currentTopSectionViewCount;
}
最主要的是所有UIScrollView以及继承与UISCrollView子控件的已经滚动的代理.
以及当前显示的"Cells".通过- (UITableViewCell *)visibleCells;
来调用.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
if (scrollView == self.tableView) {
NSArray <UITableViewCell *> *cellArray = [self.tableView visibleCells];
//cell的section的最小值
long cellSectionMINCount = LONG_MAX;
for (int i = 0; i < cellArray.count; i++) {
UITableViewCell *cell = cellArray[i];
long cellSection = [self.tableView indexPathForCell:cell].section;
if (cellSection < cellSectionMINCount) {
cellSectionMINCount = cellSection;
}
}
_currentTopSectionViewCount = cellSectionMINCount;
NSLog(@"当前悬停的组头是:%ld",_currentTopSectionViewCount);
}
}
我们可以使用UITableView的
- (nullable UITableViewHeaderFooterView *)headerViewForSection:(NSInteger)section NS_AVAILABLE_IOS(6_0);
方法来取到组头或者是组尾试图.
一般来说,小伙伴们一半肯定是创建一个UIView然后直接返回作为每一组的组头或者组尾试图.那么,大家看到上面的这个方法有没有想到那个返回值是
UITableViewHeaderFooterView
.
而UITableViewHeaderFooterView中第一个(一般最重要的东西都是放在最上面的)方法就是
- (instancetype)initWithReuseIdentifier:(nullable NSString *)reuseIdentifier NS_DESIGNATED_INITIALIZER;
看到
Identifier
是否能够联想到UITableView的Indentifier呢.registerclass的时候不知道大家是否注意到了有个headerFooter:
既然注册View和Cell的方式一样,那么取的时候也应该和Cell的方式一样:
/*
*这里只是拿HeaderView举个例子.如果大家要看footerView那么可以重写另外一个方法
*viewForFooterInSection
*/
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UITableViewHeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:tableHeaderViewID];
/// 这里headerView的初始化.
return headerView;
}
**注:**在这里取的话会有点小问题,那就是viewForHeader是在需要出现新的header的时候才会调用的.那么我们应该在下面的这个方法算出_currentTopSectionViewCount之后进行计算.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
/// 在计算完毕_currentTopSectionViewCount之后去动态设置悬浮在顶部的sectionView的属性
}