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

UITableView с фиксированными заголовками раздела

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

У меня есть UITableView внутри a UIViewController, и это, похоже, не так.

Это просто поведение defualt для UITableViewController?

Вот некоторый упрощенный код, основанный на том, что у меня есть. Я покажу интерфейс UIController и каждый метод табличного представления, который был реализован для создания представления таблицы. У меня есть класс источника вспомогательных данных, который помогает мне индексировать мои объекты для использования с таблицей.

    @interface MyUIViewController ()<UITableViewDelegate, UITableViewDataSource>
        @property (nonatomic, readonly) UITableView *myTableView;
        @property (nonatomic, readonly) MyCustomHelperDataSource *helperDataSource;
    @end

    //when section data is set, get details for each section and reload table on success
    - (void)setSectionData:(NSArray *)sections {
        super.sectionData = sections; //this array drives the sections

        //get additional data for section details
        [[RestKitService sharedClient] getSectionDetailsForSection:someId 
        success:^(RKObjectRequestOperation *operation, RKMappingResult *details) {
            NSLog(@"Got section details data");
            _helperDataSource = [[MyCustomHelperDataSource alloc] initWithSections:sections andDetails:details.array];
            [myTableView reloadData];
        } failure:^(RKObjectRequestOperation *operation, NSError *error) {
            NSLog(@"Failed getting section details");
        }];
    }

    #pragma mark <UITableViewDataSource, UITableViewDelegate>

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
        if (!_helperDataSource) return 0;
        return [_helperDataSource countSectionsWithDetails]; //number of section that have details rows, ignore any empty sections
    }

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        //get the section object for the current section int
        SectionObject *section = [_helperDataSource sectionObjectForSection:section];
        //return the number of details rows for the section object at this section
        return [_helperDataSource countOfSectionDetails:section.sectionId];
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        UITableViewCell * cell;

        NSString *CellIdentifier = @"SectionDetailCell";

        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
            cell.textLabel.font = [UIFont systemFontOfSize:12.0f];
        }

        //get the detail object for this section
        SectionObject *section = [_helperDataSource sectionObjectForSection:indexPath.section]; 

        NSArray* detailsForSection = [_helperDataSource detailsForSection:section.sectionId] ;
        SectionDetail *sd = (SectionDetail*)[detailsForSection objectAtIndex:indexPath.row];

        cell.textLabel.text = sd.displayText;
        cell.detailTextLabel.text = sd.subText;
        cell.detailTextLabel.textColor = [UIColor blueTextColor];

        return cell;
    }

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30.0f;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger) section {
    //get the section object for the current section
    SectionObject *section = [_helperDataSource sectionObjectForSection:section]; 

    NSString *title = @"%@ (%d)";

    return [NSString stringWithFormat:title, section.name, [_helperDataSource countOfSectionDetails:section.sectionId]];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 260, 0)];
    header.autoresizingMask = UIViewAutoresizingFlexibleWidth;

    header.backgroundColor = [UIColor darkBackgroundColor];

    SSLabel *label = [[SSLabel alloc] initWithFrame:CGRectMake(3, 3, 260, 24)];
    label.font = [UIFont boldSystemFontOfSize:10.0f];
    label.verticalTextAlignment = SSLabelVerticalTextAlignmentMiddle;
    label.backgroundColor = [UIColor clearColor];
    label.text = [self tableView:tableView titleForHeaderInSection:section];
    label.textColor = [UIColor whiteColor];
    label.shadowColor = [UIColor darkGrayColor];
    label.shadowOffset = CGSizeMake(1.0, 1.0);
    [header addSubview:label];

    return header;
}
4b9b3361

Ответ 1

Заголовки остаются фиксированными, если для свойства UITableViewStyle таблицы установлено значение UITableViewStylePlain. Если у вас установлено значение UITableViewStyleGrouped, заголовки будут прокручиваться с ячейками.

Ответ 2

Вы также можете установить для свойства tableback bounces значение НЕТ. Это приведет к тому, что заголовки разделов не будут плавать/статичны, но тогда вы также потеряете свойство отката таблицы.

Ответ 3

Swift 3.0

Создайте ViewController с помощью UITableViewDelegate и протоколов UITableViewDataSource. Затем создайте внутри него tableView, объявив его стиль UITableViewStyle.grouped. Это исправит заголовки.

lazy var tableView: UITableView = {
    let view = UITableView(frame: UIScreen.main.bounds, style: UITableViewStyle.grouped)
    view.delegate = self
    view.dataSource = self
    view.separatorStyle = .none
    return view
}()

Ответ 4

Измените стиль TableView:

self.tableview = [[UITableView alloc] initwithFrame: frame стиль: UITableViewStyleGrouped];

В соответствии с документацией на яблоко для UITableView:

UITableViewStylePlain - представление простой таблицы. Любые заголовки разделов или нижние колонтитулы отображаются как встроенные разделители и плавают, когда таблица просмотр прокручивается.

UITableViewStyleGrouped - представление таблицы, чьи разделы представляют разные группы строк. Верхние и нижние колонтитулы не плавают.

Надеюсь, это небольшое изменение поможет вам.

Ответ 5

Теперь ваше табличное представление выглядит как обычный стиль таблицы, но не плавает buz стиль таблицы уставок, заданный для группировки.

[_tableView setBackgroundView:nil];
_tableView.backgroundColor = [UIColor whiteColor];

Ответ 6

чтобы заголовок секции UITableView не был липким или липким:

  1. измените стиль представления таблицы - сделайте его сгруппированным для нелистового и сделайте его понятным для заголовков липких разделов - не забывайте: вы можете сделать это из раскадровки без написания кода. (нажмите на свой вид таблицы и измените стиль с помощью правого меню "Сторона/компонент")

  2. если у вас есть дополнительные компоненты, такие как пользовательские виды или т.д., пожалуйста, просмотрите поля вида таблицы, чтобы создать соответствующий дизайн. (например, высота заголовка для секций и высота ячейки на пути индекса, секции)