Как получить видимые разделы UITableView? - PullRequest
16 голосов
/ 16 ноября 2010

UITableView предоставляет методы indexPathsForVisibleRows и visibleCells, но как я могу получить видимые участки?

Ответы [ 11 ]

20 голосов
/ 10 июня 2013

Или действительно простым способом было бы воспользоваться преимуществами valueForKeyPath и класса NSSet:

NSSet *visibleSections = [NSSet setWithArray:[[self.tableView indexPathsForVisibleRows] valueForKey:@"section"]];

По сути, вы получаете массив значений раздела в видимых строках, а затем заполняете набор следующим образом:удалить дубликаты.

8 голосов
/ 19 октября 2015

Swift версия

if let visibleRows = tableView.indexPathsForVisibleRows {
    let visibleSections = visibleRows.map({$0.section})
}
7 голосов
/ 16 ноября 2010

UITableView хранят свои ячейки, используя NSIndexPath.В результате отсутствует объект для разделов.Используя следующий код, мы можем обойти таблицу и выполнить операции, используя индексы видимых разделов (я не уверен, почему вы хотите видеть видимые разделы, поскольку только видимый означает, что они в данный момент находятся на экране, но неважно).

for (NSIndexPath* i in [yourTableViewName indexPathsForVisibleRows])
{
  NSUInteger sectionPath = [i indexAtPosition:0];
  //custom code here, will run multiple times per section for each visible row in the group
}
2 голосов
/ 10 марта 2013

Извлечение разделов из списка видимых строк:

NSArray *indexPathsForVisibleRows = [tableView indexPathsForVisibleRows];
NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
for ( NSIndexPath *indexPath in indexPathsForVisibleRows ) {
     [indexSet addIndex:indexPath.section];
}
NSLog(@"indexSet %@",indexSet);
// indexSet <NSMutableIndexSet: 0x11a5c190>[number of indexes: 5 (in 1 ranges), indexes: (9-13)]

Или:

NSArray *indexPathsForVisibleRows = [detailTableView indexPathsForVisibleRows];
NSMutableSet *sectionSet = [NSMutableSet set];
for ( NSIndexPath *indexPath in indexPathsForVisibleRows ) {
    [sectionSet addObject:[NSNumber numberWithInt:indexPath.section]];
}
NSLog(@"sectionSet %@",sectionSet);
// sectionSet {(13, 11, 9, 10, 12 )}
1 голос
/ 08 октября 2015
for (NSUInteger section = 0; section < self.tableView.numberOfSections; ++section) {
    UIView *headerView = [self.tableView headerViewForSection:section];
    if (headerView.window) {
        NSLog(@"its visible");
    }
}
1 голос
/ 30 сентября 2013

Ответ намного проще и аккуратнее с помощью kvc

NSArray *visibleSections = [self.tableView.indexPathsForVisibleRows valueForKey:@"section"];

это может дать вам массив с дублирующимися значениями, но вы можете управлять оттуда.

1 голос
/ 23 августа 2013

2-шаговое решение, чтобы получить видимые секции в UITableView:

1) Добавить представления заголовков в изменяемый массив в viewForHeaderInSection
2) Обновить массив, когда просмотр таблицы прокручивается в scrollViewDidScroll

обратите внимание на использование свойства tag для хранения номера раздела

@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];
}
1 голос
/ 23 ноября 2010

У меня есть решение.

На первом шаге в каждом разделе будет отображаться UIView, созданный - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section, который будет сохранен в массиве.

Когда прокручивается TableView, я хочу освободить невидимое представление сечения, поэтомуМне нужно знать, какая секция видна или нет, следуйте коду функции, который будет обнаружен для этой цели, если вид видим, то освободите его.

-(BOOL)isVisibleRect:(CGRect)rect containerView:(UIScrollView*)containerView
{
    CGPoint point = containerView.contentOffset;
    CGFloat zy = point.y ;

    CGFloat  py =  rect.origin.y + rect.size.height;
    if (py - zy <0) {
            return FALSE;
    }
    CGRect  screenRect = containerView.frame;

    CGFloat by = screenRect.size.height + zy ;
    if (rect.origin.y > by) {
            return FALSE;
    }
    return TRUE;
}

(rect - это рамка раздела UIView; containerView - это UITableView)

Таким образом, я могу получить видимые участки UITableView, но я надеюсь, что SDK может предоставить API для этой цели напрямую.

0 голосов
/ 16 января 2019

Вы пробовали это в Swift 4?

let sections = tableView.indexPathsForVisibleRows?.map { $0.section } ?? []
for section in sections { 
    print(String(format: "%d", section)) 
}
0 голосов
/ 21 мая 2018

Swift 4.1 ?

self.sections.indices.forEach{ (i:Int) in
    let section:UIView? = self.tableView(self, viewForHeaderInSection: i)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...