UITableViewCell проверяется случайным образом, когда я прокручиваю вверх и вниз - PullRequest
0 голосов
/ 02 января 2012

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

Файл определения .h:

@interface RechercheThematiqueViewController : UIViewController{

    NSDictionary *tableContents;
    NSArray *sortedKeys;


}
//added
@property(nonatomic,copy)NSMutableArray *tableData;
//
-(IBAction)goBackToFirstView:(id)sender;
@end

Файл реализации .m:

static NSString * const kCellTextKey = @"CellTextKey";
static NSString * const kCellStateKey = @"CellStateKey";
//
#import "RechercheThematiqueViewController.h"
@implementation RechercheThematiqueViewController

@synthesize tableData;

- (void)viewDidLoad
{ 

    NSArray *tempArray = [[NSArray alloc]
                         initWithObjects:@"Mairie",@"Préfectures et sous-préfectures",@"Palais de justice",@"Commissariat de police",@"Gendarmerie",@"Caisse primaire d'assurance maladie",@"Banque",@"Centre commercial et grand magasin",@"Supermarché et hypermarché",@"Agence immobilière",@"Location d'appartement",@"Notaire",@"Discothèques",@"Casino",@"théâtre et concert",@"cinéma",@"musée",@"Bibliothèque et médiathèque",@"parc d'attraction",@"Zoo/parc animalier",@"Club de forme",@"Association et club de sport",@"Stade et complexe sportif",@"Golf",@"Tennis",@"Equitation",@"Garage auto / moto",@"Auto-école",@"Stations services",@"Hôtel",@"Camping",@"Location saisonnière",@"Village et club de vacances",@"Restaurant",@"pizzeria",@"traiteur",@"Bar",@"Restauration rapide",@"Service d'urgence",@"Médecin généraliste",@"Kiné",@"Dentiste",@"Clinique",@"Maternité",@"Pharmacies",@"Vétérinaire",@"office de tourisme",@"Visite de Sites et circuits touristiques",@"Agence de voyages",nil];
    NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:[tempArray count]];

    for(NSString * myStr in tempArray) {
        NSNumber *state = [NSNumber numberWithBool:NO];
        NSLog(@"%@",myStr);
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:myStr, kCellTextKey, state, kCellStateKey, nil];
        [arr addObject:dict];
    }

    tableData = [arr mutableCopy];

        //

    //charger le TableView
    //section1
    NSArray *arrTemp1 = [[NSArray alloc]
                         initWithObjects:@"Mairie",@"Préfectures et sous-préfectures",@"Palais de justice",@"Commissariat de police",@"Gendarmerie",@"Caisse primaire d'assurance maladie",nil];
    //section2
    NSArray *arrTemp2 = [[NSArray alloc]
                         initWithObjects:@"Banque",@"Centre commercial et grand magasin",@"Supermarché et hypermarché",nil];
    //section3
    NSArray *arrTemp3 = [[NSArray alloc]
                         initWithObjects:@"Agence immobilière",@"Location d'appartement",@"Notaire",nil];
    //section4
    NSArray *arrTemp4 = [[NSArray alloc]
                         initWithObjects:@"Discothèques",@"Casino",@"théâtre et concert",@"cinéma",@"musée",@"Bibliothèque et médiathèque",@"parc d'attraction",@"Zoo/parc animalier",nil];
    //section5
    NSArray *arrTemp5 = [[NSArray alloc]
                         initWithObjects:@"Club de forme",@"Association et club de sport",@"Stade et complexe sportif",@"Golf",@"Tennis",@"Equitation",nil];

    //section6
    NSArray *arrTemp6 = [[NSArray alloc]
                         initWithObjects:@"Garage auto / moto",@"Auto-école",@"Stations services",nil];
    //section7
    NSArray *arrTemp7 = [[NSArray alloc]
                         initWithObjects:@"Hôtel",@"Camping",@"Location saisonnière",@"Village et club de vacances",nil];
    //section8
    NSArray *arrTemp8 = [[NSArray alloc]
                         initWithObjects:@"Restaurant",@"pizzeria",@"traiteur",@"Bar",@"Restauration rapide",nil];
    //section9
    NSArray *arrTemp9 = [[NSArray alloc]
                         initWithObjects:@"Service d'urgence",@"Médecin généraliste",@"Kiné",@"Dentiste",@"Clinique",@"Maternité",@"Pharmacies",@"Vétérinaire",nil];
    //section10
    NSArray *arrTemp10 = [[NSArray alloc]
                         initWithObjects:@"office de tourisme",@"Visite de Sites et circuits touristiques",@"Agence de voyages",nil];
    NSDictionary *temp =[[NSDictionary alloc]
                         initWithObjectsAndKeys:arrTemp1,@"Administrations Enseignement",arrTemp2,
                     @"Commerces Banques",arrTemp3,@"Immobilier",arrTemp4,@"Divertissement Culture",arrTemp5,@"Sports Loisirs",arrTemp6,@"Auto - moto",arrTemp7,@"Hébergement",arrTemp8,@"Restauration",arrTemp9,@"Santé",arrTemp10,@"Tourisme",nil];

    self->tableContents =temp;
    self->sortedKeys =[[self->tableContents allKeys]
                       sortedArrayUsingSelector:@selector(compare:)];
    [super viewDidLoad];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return [self->sortedKeys count];

}

- (NSString *)tableView:(UITableView *)tableView

titleForHeaderInSection:(NSInteger)section

{

    return [self->sortedKeys objectAtIndex:section];

}



- (NSInteger)tableView:(UITableView *)table

 numberOfRowsInSection:(NSInteger)section {

    NSArray *listData =[self->tableContents objectForKey:
                        [self->sortedKeys objectAtIndex:section]];
    return [listData count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView

         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *cellIdentifier = @"CheckedTableViewCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

if (!cell) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}

NSDictionary *rowData = [self.tableData objectAtIndex:indexPath.row];
cell.textLabel.text = [rowData objectForKey:kCellTextKey];

if ([[rowData objectForKey:kCellStateKey] boolValue]) {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
    cell.accessoryType = UITableViewCellAccessoryNone;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dict = [self.tableData objectAtIndex:indexPath.row];
    BOOL newState = ![[dict objectForKey:kCellStateKey] boolValue];
    NSDictionary *newDict = [NSDictionary dictionaryWithObjectsAndKeys:[dict objectForKey:kCellTextKey], kCellTextKey, [NSNumber numberWithBool:newState], kCellStateKey, nil];
    [self.tableData replaceObjectAtIndex:indexPath.row withObject:newDict];

    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

@end

Ответы [ 2 ]

0 голосов
/ 03 января 2012

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

В любом случае, кажется, что для каждого раздела вам нужно содержимое из arrTemp1, arrTemp2, arrTemp3 .. для каждого раздела.Но, согласно вашему коду, он показывает элементы из tableData, и поэтому элементы одинаковы для каждого раздела.Единственное, так как вы получаете счетчик для каждого раздела из tableContents словаря, счетчик меняется.

Так что вам, возможно, придется взглянуть на логику в - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath, нужно ли показывать содержимое из tableData или tableContents.Если вы используете tableData, элементы одинаковы, и поэтому, если вы отметите один раздел, он будет отражен во всех разделах.

0 голосов
/ 02 января 2012

ваша ячейка не выпущена автоматически:

cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];

может быть, это ошибка?

, и вы должны отменить выбор ячейки в:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  [tableView deselectRowAtIndexPath:indexPath animated:YES];
...
...

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