114 votes

UITableView avec des en-têtes de section fixes

Salue, Je lis que le comportement par défaut de UITableView est d'épingler les lignes d'en-tête des sections en haut du tableau lorsque vous faites défiler les sections jusqu'à ce que la section suivante fasse disparaître la ligne de la section précédente.

J'ai un UITableView à l'intérieur d'un UIViewController et cela ne semble pas être le cas.

Est-ce que c'est juste le comportement habituel pour UITableViewController ?

Voici un code simplifié basé sur ce que j'ai. Je vais montrer le UIController et chaque méthode de vue de la table que j'ai implémentée pour créer la vue de la table. J'ai une classe de source de données auxiliaire qui m'aide à indexer mes objets pour les utiliser avec la table.

    @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;
}

334voto

bachonk Points 768

Les en-têtes ne restent fixes (flottants) que lorsque l'option UITableViewStyle de la table est définie comme UITableViewStylePlain .

Si vous l'avez réglé sur UITableViewStyleGrouped les en-têtes défileront vers le haut avec les cellules (ils ne flotteront pas).

5voto

Aks Points 369

Changez le style de votre TableView :

self.tableview = [[UITableView alloc] initwithFrame:frame style:UITableViewStyleGrouped] ;

Conformément à la documentation d'Apple pour UITableView :

UITableViewStylePlain- Une vue de table simple. Tout en-tête de section ou de section sont affichés comme des séparateurs de ligne et flottent lorsque la table défilement de la vue tableau.

UITableViewStyleGrouped- Une vue de table dont les sections présentent des groupes de lignes groupes de lignes distincts. Les en-têtes et pieds de section ne sont pas flottants.

J'espère que ce petit changement vous aidera

3voto

Swift 3.0

Créer un ViewController avec le UITableViewDelegate y UITableViewDataSource les protocoles. Créez ensuite un tableView à l'intérieur de celui-ci, en déclarant que son style sera UITableViewStyle.grouped . Cela corrigera les en-têtes.

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
}()

0voto

kevinl Points 1012

Vous pouvez également définir la propriété bounces de la tableview sur NO. Ainsi, les en-têtes de section resteront non flottants/statiques, mais vous perdrez également la propriété de rebond de la vue tableau.

0voto

Burcu Kirik Points 19

Pour rendre l'en-tête des sections de UITableView non collant ou collant :

  1. changez le style de la vue tableau - rendez-la groupée pour les titres de section non collants et unie pour les titres de section collants - n'oubliez pas : vous pouvez le faire à partir du storyboard sans écrire de code. (cliquez sur votre vue tableau et changez son style à partir du menu latéral droit / composant)

  2. si vous avez des composants supplémentaires tels que des vues personnalisées ou autres, veuillez vérifier les marges de la vue tableau pour créer un design approprié. (comme la hauteur de l'en-tête pour les sections et la hauteur de la cellule au chemin d'index, sections)

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X