Какая строка в моем секционном представлении таблицы? - PullRequest
1 голос
/ 25 июля 2011

В одной руке у меня есть список, в котором корневой ключ - это массив из 12 элементов. Во второй руке у меня есть секционное представление таблицы (с 3 разделами MOTIF-COULEUR-OTHER) Что я хочу, так это чтобы табличные таблицы правильно отображали данные в разделах. в первом разделе я хочу иметь пункты 0,1,2,3 моего списка во втором разделе я хочу иметь пункты 4,5,6,7,8,9,10 моего списка в последнем разделе я хочу, чтобы пункты 11 и 12

Может быть, это действительно просто, но я просто потерпел крах

это мой RootViewController.h & .m

//
//  RootViewController.h
//  FichesRaces
//
//  Created by a3116b on 28/05/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface RootViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate> {
        NSArray *tabWebSites;


}

@property (nonatomic, retain) NSArray *tabWebSites;








@end

.m

//
//  RootViewController.m
//  FichesRaces
//
//  Created by a3116b on 28/05/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "RootViewController.h"
#import "CatsList.h"
#import "DetailViewController.h"

@implementation RootViewController
@synthesize tabWebSites;







- (void)viewDidLoad {
    [super viewDidLoad];

    // Charger le fichier .plist dans un tableau que l'on appelera  arrayFromFile
    NSString *path = [[NSBundle mainBundle] pathForResource:@"cats" ofType:@"plist"];
    NSDictionary *dictFromFile = [[NSDictionary alloc] initWithContentsOfFile:path];
    NSArray *arrayFromFile = [dictFromFile objectForKey:@"Root"];

    // Créons un tableau temporaire que nous allons remplir avec un objet Website par NSDictionnary contenu dans le fichier .plist
    // Notez l'utilisation de NSEnumerator pour parcourir un tableau
    NSMutableArray *websitesToAdd = [[NSMutableArray alloc] init];
    NSEnumerator *enumerator = [arrayFromFile objectEnumerator];
    NSDictionary *anObject;
    while ((anObject = [enumerator nextObject])) {
        CatsList *cl = [[CatsList alloc] initWithDictionaryFromPlist: anObject];
        [websitesToAdd addObject: cl];
        [cl release];
    }

    // Remplir la propriété tabWebSites avec le contenu du NSMutableArray précédent
    self.tabWebSites = [NSArray arrayWithArray:websitesToAdd];

    // Gestion de la mémoire : pour chaque alloc, n'oubliez pas le release qui va avec !
    [websitesToAdd release];
    [arrayFromFile release];
}




- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}



- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    if ( section == 0 ) return @"Les Motifs";
    if ( section == 1 ) return @"Les Couleurs";
    if ( section == 2 ) return @"Bon à Savoir";

    return @"";

   // return [sectionHeaders objectAtIndex:section];
}






// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 4;
            break;

        case 1:
            return 13;
            break;

        default:
            return 3;
            break;
    }

   }





// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";
    if (indexPath.section == 2) {
        CellIdentifier = @"cell";
    }


    // Les cellules sont mises en cache pour accélérer le traitement, sous l'identifiant "Cell",
    // on essaie récupère ce modèle de cellule s'il est déjà en cache
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Si on n'a pas réussi à sortir une cellule du cache, on crée un nouveau modèle de cellule
    // et on l'enregistre dans le cache
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];



     /*    (indexPath.section == 0 && indexPath.row ==0);
         (indexPath.section == 1 && indexPath.row == 5);
         (indexPath.section == 2 && indexPath.row == 13);*/

   /*     //-----------------------------------------------

        NSUInteger sectionNumber = [indexPath section];
        NSUInteger rowNumber = [indexPath row];  

        // determine the correct row.
        // it will be restarted from 0 every time, and as
        // we're just loading in from one array, we need to
        // offset it by the right amount depending on the section.
        //  int sectionNumber = indexPath.row;
        if ( sectionNumber == 0 ) rowNumber = 4;
        if ( sectionNumber == 1 ) rowNumber = +5;
        if ( sectionNumber == 2 ) rowNumber = +18;


        //-----------------------------------------------   */


    }





    // On récupère l'objet Website qui correspon à la ligne que l'on souhaite afficher
    CatsList *cl = [self.tabWebSites objectAtIndex:indexPath.row];

    // On configure la cellule avec le titre du site et sa description
    cell.textLabel.text = cl.TITLE;
    cell.detailTextLabel.text = cl.DESCRIPTION;


    //important ajouter signalisation sinon APP REFUSE

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    // On renvoie la cellule configurée pour l'affichage
    return cell;
}



/*- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 3) {
        return nil;
    }
    return indexPath;
}*/





- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{



    DetailViewController *detailVC = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    detailVC.CL = [self.tabWebSites objectAtIndex:indexPath.row];

    [self.navigationController pushViewController:detailVC animated:YES];
    [detailVC release];
}






- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload
{
    [super viewDidUnload];

    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}

- (void)dealloc
{
    [super dealloc];
}

@end

Спасибо, ваши ответы очень полезны для меня

Ответы [ 2 ]

1 голос
/ 25 июля 2011

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

// On récupère l'objet Website qui correspon à la ligne que l'on souhaite afficher
CatsList *cl = [self.tabWebSites objectAtIndex:indexPath.row];

Вы могли бы сделать:

CatsList *cl = [self.tabWebSites objectAtIndex:[self linearIndexFromIndexPath:indexPath]];

где linearIndexFromIndexPath: будет определено, например, так:

- (NSUInteger)linearIndexFromIndexPath:(NSIndexPath*)indexPath {
    NSUInteger result = 0;
    for (int i = 0; i < indexPath.section ; i++) {
         result += [self numberOfSectionsInTableView:self.tableView];
    }
    return result + indexPath.row;
}

или что-то подобное. Обратите внимание, что в моей реализации я решил не жестко кодировать количество строк в каждом разделе, а извлекать их с помощью метода делегата. Это делает код более сложным, но более устойчивым к изменениям.

0 голосов
/ 25 июля 2011

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 4;
            break;

        case 1:
            return 7;
            break;

        default:
            return 2;
            break;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...