UICollectionViewCell one of the section from UICollectionView Cell Repeating same cell for multiple times

久未见 提交于 2019-12-20 07:02:25

问题


I have an old project done by a developer some times ago.. This particular project has 3 collection views such as collectionAnnouncments, collectionNews and collectionBulletin.

The first collectionview collectionAnnouncments is loading a same cell 10 times. But other two sections loading the cell correctly one time as per the response count.

I don't have any idea up to now for this problem. I tried some solutions from the google but I couldn't sorted because of the bad UI and Code implementation by that developer.

Ex- He used one UICollectionView Inside a tableview and using UICollectionView Class for all 3 collectionview and used a general cell for all collectionviews.

declaration... in m file

    __weak IBOutlet UITableView *table;
        UICollectionView *collectionAnnouncments, *collectionBulletin, 
*collectionNews;

Please check the following codes and provide me a better simple solution to fix this issue without any major modifications or re-implementation because I don't have time for that.

  - (void)viewDidLoad {
    [super viewDidLoad];

    self.automaticallyAdjustsScrollViewInsets = NO;

    home.title=[Utilities getLocalizedStringForKey:@"Home"];

    [Utilities setNavigationController:self];
    //self.label.text=NSLocalizedFailureReasonErrorKey
    self.navigationItem.leftBarButtonItem = nil;
    __block BOOL newsDone = NO, bulletInDone = NO, announcmentDone = NO, refreshed = NO;

    collectionViewDic = [[NSMutableDictionary alloc]init];
    [Utilities serverRequest:@{@"getNewsfeed":@"a6dba37437ced2c3b07469fd6c0661f3"} completionBlock:^(id response) {

        collectionViewDic[@"news"] = response[@"response"];
        NSArray *responseValues = [response[@"response"] allValues]; // An NSArray of NSArrays
        NSMutableArray *dictionarys = [NSMutableArray new];
        for (NSArray *dictArrays in responseValues) {
            for (NSDictionary *dict in dictArrays) {
                [dictionarys addObject:dict];
            }
        }
        _newsArray = dictionarys;
        NSLog(@"news%@",dictionarys);

        // sorting to newest
        NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"nf_id" ascending:NO];
        _sortednewsArray = [_newsArray sortedArrayUsingDescriptors:@[sortDescriptor]];
        NSLog(@"Sorted news Response -%@", _sortednewsArray);

        //Registeriing the collectionview custom cell
    //    [UICollectionView registerClass:[CustomCell class] forCellWithReuseIdentifier:@"customCell"];
    //   [collectionAnnouncments registerClass:[CustomCell class] forCellWithReuseIdentifier:@"customCell"];


    //    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"Cell"];

        newsDone = YES;
        if (newsDone && bulletInDone && announcmentDone && !refreshed) {
            refreshed = YES;
            [table reloadData];
        }

    } errorBlock:nil];

    [Utilities serverRequest:@{@"getBulletin":@"a6dba37437ced2c3b07469fd6c0661f3"} completionBlock:^(id response) {
        //   NSString *bulletinID = @"wb_id";

        collectionViewDic[@"bulletin"] = response[@"response"];
        NSArray *responseValues = [response[@"response"] allValues]; // An NSArray of NSArrays
        NSMutableArray *dictionarys = [NSMutableArray new];
        for (NSArray *dictArrays in responseValues) {
            for (NSDictionary *dict in dictArrays) {
                [dictionarys addObject:dict];
            }
        }
        _bulletinArray = dictionarys;
        NSLog(@"bulletin%@",dictionarys);

        // sorting to newest
        NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"wb_id" ascending:NO];
        _sortedbulletinArray = [_bulletinArray sortedArrayUsingDescriptors:@[sortDescriptor]];
        NSLog(@"Sorted bulletin Response -%@", _sortedbulletinArray);

        bulletInDone = YES;
        if (newsDone && bulletInDone && announcmentDone && !refreshed) {
            refreshed = YES;
            [table reloadData];
        }
    } errorBlock:nil];

    [Utilities serverRequest:@{@"getAnnouncement":@"a6dba37437ced2c3b07469fd6c0661f3"} completionBlock:^(id response) {

        collectionViewDic[@"announcement"] = response[@"response"];
        NSArray *responseValues = [response[@"response"] allValues]; // An NSArray of NSArrays
        NSMutableArray *dictionarys = [NSMutableArray new];
        for (NSArray *dictArrays in responseValues) {
            for (NSDictionary *dict in dictArrays) {
                [dictionarys addObject:dict];
            }
        }
        _annArray = dictionarys;
        NSLog(@"AnnouncementResponse%@",dictionarys);
        NSLog(@" Ann ID%@", [dictionarys valueForKey:@"anc_id"]);
        // sorting to newest
        NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date_added" ascending:NO];
        _sortedAnnArray = [_annArray sortedArrayUsingDescriptors:@[sortDescriptor]];
        NSLog(@"Sorted Array Response -%@", _sortedAnnArray);
        NSLog(@"Sorted Ann Array-count%zd",_sortedAnnArray.count);
        NSLog(@"Sorted Ann ID%@", [_sortedAnnArray valueForKey:@"anc_id"]);

        announcmentDone = YES;
        if (newsDone && bulletInDone && announcmentDone && !refreshed) {
            refreshed = YES;
            [table reloadData];
        }
    } errorBlock:nil];

    menuView = [Utilities addMenuView:self];
}

-(void)getNewsFeed
{
    collectionViewDic = [[NSMutableDictionary alloc]init];
    [Utilities serverRequest:@{@"getNewsfeed":@"a6dba37437ced2c3b07469fd6c0661f3"} completionBlock:^(id response) {

        if(response != nil)
        {
            if ([response isKindOfClass:[NSString class]]) {
                // print response .
                NSLog(@"MAIN RESPONSE!%@",response);
            }
            //on successfully response, which provided dictionary,

            else if ([[response objectForKey:@"success"] boolValue] == true) {
                // on true print response data.
                collectionViewDic[@"news"] = response[@"response"];

                NSArray *responseValues = [response[@"response"] allValues]; // An NSArray of NSArrays
                NSMutableArray *dictionarys = [NSMutableArray new];
                for (NSArray *dictArrays in responseValues) {
                    for (NSDictionary *dict in dictArrays) {
                        [dictionarys addObject:dict];
                    }
                }
                _newsArray = dictionarys;
                NSLog(@"news%@",dictionarys);

                // sorting to newest
                NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"nf_id" ascending:NO];
                _sortednewsArray = [_newsArray sortedArrayUsingDescriptors:@[sortDescriptor]];
                NSLog(@"Sorted news Response -%@", _sortednewsArray);
            }
            //on success response, with failure message which is false.
            else if ([[response objectForKey:@"success"] boolValue] == false) {
                // handle error on success is false.

            }

        }

    } errorBlock:nil];
}



-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section  {


        @try {
        NSString *key = @"";
        if ([collectionView isEqual:collectionNews])
        key = @"news";
        else if ([collectionView isEqual:collectionAnnouncments])
        key = @"announcement";
        else if ([collectionView isEqual:collectionBulletin])
        key = @"bulletin";
        NSDictionary *mainDic = collectionViewDic[key];
        NSArray *array = mainDic[ [mainDic allKeys][0] ];

        return [array count];

    } @catch (NSException *exception) {
        return 0;
    }


}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    @try {

        //NSString *key = @"";
        if ([collectionView isEqual:collectionNews])

            return _sortednewsArray.count;


        else if ([collectionView isEqual:collectionAnnouncments])
            return _sortedAnnArray.count;

        else if ([collectionView isEqual:collectionBulletin])
            return _sortedbulletinArray.count;

    }
    @catch (NSException *exception) {
        return 0;
    }

  // return _sortedAnnArray.count + _sortednewsArray.count + _sortedbulletinArray.count;
 //   return [[collectionViewDic allKeys] count];
  //  return 50;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"generalCell" forIndexPath:indexPath];
  // CustomCell *cell = (CustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"customCell" forIndexPath:indexPath];
   // cell.tag = indexPath.row;
    [cell setTag:indexPath.row];
    //UILabel *test = [cell.contentView viewWithTag:1];
    UIImageView *image = [cell.contentView viewWithTag:1];
    //UILabel *cellTitle = [cell.contentView viewWithTag:2];
    //UILabel *cellHead =[cell.contentView viewWithTag:2];


    if ([collectionView isEqual:collectionAnnouncments]) {

     //  NSDictionary *mainDic = collectionViewDic[@"announcement"];
      //  NSArray *array = mainDic[ [mainDic allKeys][indexPath.section] ];
         NSDictionary *dic = _sortedAnnArray[indexPath.section] ;

        collectionAnnouncments.delegate = self;
        collectionAnnouncments.dataSource = self;


       // cellHead.text =@"Announcements";
        //cellTitle.text = dic[@"anc_title"];
        if ([dic[@"announcement_images"] count] > 0)
            [image setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",ANNOUNCMENT_IMAGES_URL,dic[@"announcement_images"][0][@"wi_image"] ]  ]] ;
    }


    else if([collectionView isEqual:collectionNews]) {
        //cellHead.text =@"News";
     //  NSDictionary *mainDic = collectionViewDic[@"news"];
     //  NSArray *array = mainDic[ [mainDic allKeys][0] ];



        NSDictionary *dic = _sortednewsArray[indexPath.section] ;

        collectionNews.delegate = self;
        collectionNews.dataSource = self;

        //cellTitle.text = dic[@"nf_title"];
        if ([dic[@"newsfeed_images"] count] > 0)
            [image setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",NEWS_IMAGES_URL,dic[@"newsfeed_images"][0][@"wi_image"] ]  ]] ;
    }

    else if([collectionView isEqual:collectionBulletin]) {

     //  NSDictionary *mainDic = collectionViewDic[@"bulletin"];
    //    NSArray *array = mainDic[ _sortedbulletinArray[indexPath.section] ];



        NSDictionary *dic = _sortedbulletinArray[indexPath.section] ;
        collectionBulletin.delegate = self;
        collectionBulletin.dataSource = self;
       // cellTitle.text = dic[@"wb_title"];
        if ([dic[@"bulletin_images"] count] > 0)

        if ([dic[@"bulletin_images"][0][@"wi_type"] isEqualToString:@"video"]) {

            [image setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",BULLETIN_IMAGES_URL,dic[@"ws_thumb"] ]  ]] ;

        }
        else{
[image setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",BULLETIN_IMAGES_URL,dic[@"bulletin_images"][0][@"wi_image"] ]  ]] ;
        }
    }

    return cell;
}
#pragma mark UITableView Delegate, DataSource

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  [[collectionViewDic allKeys] count];
}

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableCell"];
    cell.tag = indexPath.row;
    UICollectionView *c = [cell.contentView viewWithTag:111];

    //c.scrollEnabled = NO;

    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
    flow.minimumLineSpacing = flow.minimumInteritemSpacing = 0.0f;

    flow.itemSize = CGSizeMake([UIScreen mainScreen].bounds.size.width/1, c.bounds.size.height);
    flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
   // c.collectionViewLayout = flow;

    UIView *header = [cell.contentView viewWithTag:1];
    UIImageView *headerImage = [header viewWithTag:2];
    UILabel *headerTitle = [header viewWithTag:3];
    //NSLog(cell.tag);
    switch (indexPath.row) {
        case 0:
            //NSLog(@"text");
            headerImage.image = [UIImage imageNamed:@"Announcemets"];
            //headerTitle.text = @"Announcments";
            headerTitle.text=[Utilities getLocalizedStringForKey:@"Announcement"];
            // NSLog(headerTitle.text);
            collectionAnnouncments = c;
            [collectionAnnouncments setCollectionViewLayout:flow];
            collectionAnnouncments.delegate = self;
            collectionAnnouncments.dataSource = self;
            [collectionAnnouncments reloadData];
           // NSLog(@"text");
            break;
        case 1:
            headerImage.image = [UIImage imageNamed:@"News"];
           headerTitle.text=[Utilities getLocalizedStringForKey:@"Bussiness Highlight"];
            collectionNews = c;
            [collectionNews setCollectionViewLayout:flow];
            collectionNews.delegate = self;
            collectionNews.dataSource = self;
            [collectionNews reloadData];
             //NSLog(@"text");
            break;
        case 2:
            headerImage.image = [UIImage imageNamed:@"Bulletin"];
            headerTitle.text=[Utilities getLocalizedStringForKey:@"Bulletin Board"];
            collectionBulletin = c;
            [collectionBulletin setCollectionViewLayout:flow];
            collectionBulletin.delegate = self;
            collectionBulletin.dataSource = self;
            [collectionBulletin reloadData];
             //NSLog(@"text");
            break;

        default:
            break;
    }

    return cell;

}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.destinationViewController isKindOfClass:[NewsListing class]]) {
        NewsListing *c = segue.destinationViewController;
        NSInteger row = ((UIButton *)sender).superview.superview.superview.tag;

        if (row == 0) {
            c.isAnnouncement = YES;
            c.listingArray = collectionViewDic[@"announcement"];
        }
        else if (row == 1) {
            c.isNews = YES;
            c.listingArray = collectionViewDic[@"news"];
        }
        else if (row == 2) {
            c.isBulletin = YES;
            c.listingArray = collectionViewDic[@"bulletin"];
        }

    }

    if ([segue.destinationViewController isKindOfClass:[NewsDetail class]]) {
        NewsDetail *c = segue.destinationViewController;
        UICollectionViewCell *cell = sender;

        NSInteger row = ((UIButton *)sender).superview.superview.superview.tag;

        if (row == 0) {
            c.isAnnouncement = YES;

          //  NSDictionary *months = collectionViewDic[@"announcement"];
            NSIndexPath *indexPath = [collectionAnnouncments indexPathForCell:cell];
          //  NSArray *month = months[[months allKeys][0] ];
            NSArray *month = _sortedAnnArray;
            c.detailDic = month[indexPath.section ];
        }
        else if (row == 1) {
            c.isNews = YES;
         //   NSDictionary *months = collectionViewDic[@"news"];

            NSIndexPath *indexPath = [collectionNews indexPathForCell:cell];
          //  NSArray *month = months[[months allKeys][0] ];
            NSArray *month = _sortednewsArray;
            c.detailDic = month[indexPath.section ];

        }
        else if (row == 2) {
            c.isBulletin = YES;
          //  NSDictionary *months = collectionViewDic[@"bulletin"];
            NSIndexPath *indexPath = [collectionBulletin indexPathForCell:cell];
           // NSArray *month = months[[months allKeys][0] ];
            NSArray *month = _sortedbulletinArray;
            c.detailDic = month[indexPath.section ];
        }


    }
}

@end

来源:https://stackoverflow.com/questions/48537544/uicollectionviewcell-one-of-the-section-from-uicollectionview-cell-repeating-sam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!