2015-03-16 4 views
0

У меня возникла странная проблема, когда я выполняю действие (кнопка) reloadData моего UICollectionView, ячейки отображаются некорректно, только фоновое изображение ячеек в порядке.UICollectionView reloadData не работает правильно

Мой «INVPropertyCell» состоит из фонового изображения и двух ярлыков (название & цена). Когда я выполняю reloadData, вышеуказанные ярлыки из ячеек исчезают случайным образом.

Я сделал много поисков на разных форумах, у некоторых людей такая же проблема, но я не нашел исправления.

Ниже вы найдете мой код, если кто-то может мне помочь, он будет очень признателен.

Jérôme.

- (void)viewDidLoad 
{ 
    NSLog (@"INVPropertiesViewController -- viewDidLoad"); 


    [super viewDidLoad]; 

    // Enregistrement de la cellule. 
    [self.clProperties registerNib:[UINib nibWithNibName:@"INVPropertyCell" bundle:nil] forCellWithReuseIdentifier:@"propertyCell"]; 

    // Enregistrement du header de section 
    [self.clProperties registerNib:[UINib nibWithNibName:@"INVPropertyHeaderSection" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerCollectionCell" ]; 


    self.clProperties.delegate = self; 
    self.clProperties.dataSource =self; 


    NSLog (@"INVPropertiesViewController -- End of viewDidLoad"); 
} 

- (void)viewWillAppear:(BOOL)animated 
{ 
    NSLog (@"INVPropertiesViewController -- viewWillAppear"); 

    [super viewWillAppear:animated]; 

    categoryDictionary = [ServiceDatas getCategoriesDictionary]; 
    tblProperties = [(NSArray*)[ServiceDatas getListPropertiesByLieuFromLocalDataStore:self.selectedResidence] mutableCopy]; 

    if(tblProperties.count==0 & self.selectedResidence.propertiesCount.longValue >0) 
     tblProperties = [(NSArray*)[ServiceDatas getListPropertiesByLieuFromServer:self.selectedResidence] mutableCopy]; 

    tblPropertiesByCategory = [ServiceDatas createCategoryBreakDown:tblProperties]; 

    keysCategories = [tblPropertiesByCategory allKeys]; 


    [self.clProperties reloadData]; 


    NSLog (@"INVPropertiesViewController -- End of viewWillAppear"); 
} 


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{ 
    // [self.clProperties.collectionViewLayout invalidateLayout]; 
    return tblPropertiesByCategory.count; 
} 

- (UICollectionReusableView *)collectionView: (UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{ 

    UICollectionReusableView *reusableview = nil; 

    if(kind == UICollectionElementKindSectionHeader){ 


     INVPropertyHeaderSection *headerSection = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerCollectionCell" forIndexPath:indexPath]; 

     id categoryId = [keysCategories objectAtIndex:indexPath.section]; 

     CategoryModel *category = categoryDictionary[categoryId]; 

     if(category!=nil){ 

      headerSection.backgroundColor = [Utils colorFromHexString:category.color]; 
      headerSection.lblCategory.text = [category.title uppercaseString]; 

     } 


     reusableview = headerSection; 


    }else if(kind == UICollectionElementKindSectionFooter){ 

     if (reusableview==nil) { 
      reusableview=[[UICollectionReusableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)]; 
     } 

    } 

    return reusableview; 
} 


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section 
{ 
    // Return the number of rows in the section. 

    id categoryId = [keysCategories objectAtIndex:section]; 
    NSMutableArray *tblProperties = [tblPropertiesByCategory objectForKey:categoryId]; 


    return [tblProperties count]; 

} 

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: 
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    INVPropertyCell *cell = nil; 

    id categoryId = [keysCategories objectAtIndex:indexPath.section]; 

    NSMutableArray *tblProperties = [tblPropertiesByCategory objectForKey:categoryId]; 


    if(tblProperties!=nil){ 

     cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"propertyCell" forIndexPath:indexPath]; 

     PropertyModel *property = [tblProperties objectAtIndex:indexPath.item]; 

     NSLog(@"Ligne %ld - Colonne %ld - Lieux %@",indexPath.section, (long)indexPath.item, property.title); 

     CategoryModel *category = categoryDictionary[categoryId]; 

     if(category!=nil){ 

      [cell initWithProperty:property backgroundColor:[Utils colorFromHexString:category.color]]; 

     } 


    } 


    return cell; 

} 

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{ 

    // Récupération du bien courant. 
    id categoryId = [keysCategories objectAtIndex:indexPath.section]; 

    NSMutableArray *tblProperties = [tblPropertiesByCategory objectForKey:categoryId]; 

    PropertyModel *property = [tblProperties objectAtIndex:indexPath.row]; 

    NSLog(@"Property sélectionnée : %@",property.title); 

    self.selectedProperty = property; 

    if(property!=nil && [property.title isEqualToString:EMPTY_PROPERTY]){ 
     self.selectedProperty = nil; 
    } 

    // Déclenche le Segue pour aller à l'écran "Property" 
    [self performSegueWithIdentifier:@"segueEditPropertyView" sender:self]; 

} 

// Layout: Set cell size 
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { 

    CGSize mElementSize = CGSizeMake(107, 106); 

    if(indexPath.item==0){ 
     mElementSize = CGSizeMake(106, 106); 
    } 

    return mElementSize; 
} 

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section { 
    return 0.0; 
} 

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section { 
    return 0.0; 
} 

// Layout: Set Edges 
- (UIEdgeInsets)collectionView: 
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section { 
    return UIEdgeInsetsMake(0,0,0,0); // top, left, bottom, right 
} 

- (IBAction)btnRefresh:(id)sender { 

    [self.clProperties reloadData]; 

} 
+0

Что происходит с вашей ячейкой после перезагрузки? можете ли вы добавить скриншот того, что вы хотите, и что происходит? – DilumN

+1

Также registerNib in viewDidLoad & reloading ваши данные в viewWillAppear кажется неправильным, потому что во время выполнения viewWillAppear для вашего CollectionView не будет registerNib. Так что лучше перезагрузить коллекциюView внутри viewDidAppear – DilumN

+0

Привет, я пробовал ваш совет, но у меня все еще есть проблема. К сожалению, я не могу загрузить снимок экрана, чтобы проиллюстрировать поведение (я новичок, у меня недостаточно репутации). Я добавил некоторые дополнительные комментарии к моему сообщению для точности. –

ответ

0

я думаю, вы должны зарегистрировать класс перед регистром пера как для INVPropertyCell и INVPropertyHeaderSection клетки.

+0

Привет, я последовал твоему совету, к сожалению, у меня все еще есть проблема. –

0

Вы пытаетесь проверить и Alloc ячейки, если она равна нулю в collectionView..cellForItemAtIndexPath

cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"propertyCell" forIndexPath:indexPath]; 
if (cell == null) { 
    Array *xibs = [[NSBundle mainBundle] loadNibWithNamed:@"propertycell" 
...]; 
cell = xibs[0]; 
} 

я кодирования в быстры, так что, может быть выше синтаксис является неправильным, но это идея :)

Смежные вопросы