How to get a UITableView's visible sections?

前端 未结 12 1799
轻奢々
轻奢々 2020-12-14 19:24

UITableView provides the methods indexPathsForVisibleRows and visibleCells, but how can I get the visible sections?

12条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 20:29

    2 step solution to get the visible sections in a UITableView:

    1) Add the header views to a mutable array in viewForHeaderInSection
    2) Update the array when the tableview scrolls in scrollViewDidScroll

    note the use of the tag property to hold the section number

    @property (nonatomic, strong, readwrite) NSMutableArray *headerArray;
    
    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 40)];
        headerView.backgroundColor = [UIColor greenColor];
        headerView.tag = section;
        [_headerArray addObject:headerView];
        return headerView;
    }
    
    - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
        [self updateHeaderArray];
        NSLog(@"------------");
        for (UIView *view in _headerArray) {
            NSLog(@"visible section:%d", view.tag);
        }
    }
    
    - (void)updateHeaderArray {
        // remove invisible section headers
        NSMutableArray *removeArray = [NSMutableArray array];
        CGRect containerRect = CGRectMake(_tableView.contentOffset.x, _tableView.contentOffset.y,
                                          _tableView.frame.size.width, _tableView.frame.size.height);
        for (UIView *header in _headerArray) {
            if (!CGRectIntersectsRect(header.frame, containerRect)) {
                [removeArray addObject:header];
            }
        }
        [_headerArray removeObjectsInArray:removeArray];
    }
    

提交回复
热议问题