Подтвердить что ты не робот

Раздел перезагрузки UITableView

Я хочу перезагрузить только один раздел, а не полную таблицу. Есть ли способ в UITableView.

[tableView reloadData] используется для загрузки полной таблицы.
Я хочу знать, как загружать только один раздел, поскольку у меня есть большое количество строк в таблице.

4b9b3361

Ответ 1

Да, есть:

- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation

Ответ 2

Метод reloadSections вызывает ошибку - поскольку мне нужно построить несколько объектов. Это здорово, если вам нужна гибкость, но иногда мне также просто нужна простота. Это происходит следующим образом:

NSRange range = NSMakeRange(0, 1);
NSIndexSet *section = [NSIndexSet indexSetWithIndexesInRange:range];                                     
[self.tableView reloadSections:section withRowAnimation:UITableViewRowAnimationNone];

Это перезагрузит первый раздел. Я предпочитаю иметь категорию в UITableView и просто вызывать этот метод:

[self.tableView reloadSectionDU:0 withRowAnimation:UITableViewRowAnimationNone];

Метод моей категории выглядит следующим образом:

@implementation UITableView (DUExtensions)

- (void) reloadSectionDU:(NSInteger)section withRowAnimation:(UITableViewRowAnimation)rowAnimation {
    NSRange range = NSMakeRange(section, 1);
    NSIndexSet *sectionToReload = [NSIndexSet indexSetWithIndexesInRange:range];                                     
    [self reloadSections:sectionToReload withRowAnimation:rowAnimation];
}

Ответ 3

Но вы можете перезагрузить только те разделы, которые содержат одинаковое количество строк (или вам нужно их вручную добавить или удалить). В противном случае вы получите:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 2. The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (0), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

Что не требуется при использовании [tableView reloadData].

Когда вам нужно перезагрузить раздел, и вы изменили количество строк внутри него, вы можете использовать что-то вроде этого:

NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:section];

[self beginUpdates];
    [self deleteSections:indexSet withRowAnimation:rowAnimation];
    [self insertSections:indexSet withRowAnimation:rowAnimation];
[self endUpdates];

Если вы поместите его в категорию (например, шоу bandejapaisa), это может выглядеть так:

- (void)reloadSection:(NSInteger)section withRowAnimation:(UITableViewRowAnimation)rowAnimation {
    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:section];

    [self beginUpdates];
        [self deleteSections:indexSet withRowAnimation:rowAnimation];
        [self insertSections:indexSet withRowAnimation:rowAnimation];
    [self endUpdates];
}

Ответ 4

что правильный путь:

[self.tableView beginUpdates]; 
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];

Ответ 5

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

[self.tableView reloadData];
NSRange range = NSMakeRange(0, [self numberOfSectionsInTableView:self.tableView]);
NSIndexSet *sections = [NSIndexSet indexSetWithIndexesInRange:range];
[self.tableView reloadSections:sections withRowAnimation:UITableViewRowAnimationFade];

В моем случае мне пришлось вынудить reloadData до анимации раздела, потому что базовые данные для таблицы изменились. Тем не менее, он анимирует.

Ответ 6

Для Swift 3 и Swift 4

let sectionToReload = 1
let indexSet: IndexSet = [sectionToReload]

self.tableView.reloadSections(indexSet, with: .automatic)

Ответ 7

Вам нужно это... Для строки обновления

- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

или для раздела "Обновить"

- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation

Ответ 8

Попробуйте использовать

[self.tableView beginUpdates]; 
[self.tableView endUpdates];

Надеюсь, что это решит вашу проблему.

Ответ 9

Вот этот метод, вы можете передавать детали раздела по-разному

[self.tableView reloadSections:[[NSIndexSet alloc] initWithIndex:1] withRowAnimation:NO];

[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];

Перезагрузка отдельных разделов повышает производительность для представления таблиц, а также позволяет избежать некоторых проблем, таких как плавающие/перемещающиеся пользовательские верхние колонтитулы в вашем представлении. SO пытаться использовать reloadSection, чем relaodData, когда это возможно

Ответ 10

Если у вас есть пользовательский раздел, вы можете добавить к нему слабую ссылку в своем контроллере просмотра и обновлять его, когда захотите. Вот мой код для справки:

@property (weak, nonatomic) UILabel *tableHeaderLabel;

....

-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UITableViewHeaderFooterView *myHeader = [[UITableViewHeaderFooterView alloc] init];

    UILabel *titleLabel = [[UILabel alloc] init];
    [titleLabel setFrame:CGRectMake(20, 0, 280, 20)];
    [titleLabel setTextAlignment:NSTextAlignmentRight];
    [titleLabel setBackgroundColor:[UIColor clearColor]];
    [titleLabel setFont:[UIFont systemFontOfSize:12]];

    [myHeader addSubview:titleLabel];

    self.tableHeaderLabel = titleLabel; //save reference so we can update the header later

    return myHeader;
}

Затем вы можете обновить свой раздел следующим образом:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.tableHeaderLabel.text = [NSString stringWithFormat:@"Showing row: %ld", indexPath.row];
}