【问题标题】:UICollectionView datasource method not called after reload data重新加载数据后未调用 UICollectionView 数据源方法
【发布时间】:2015-11-08 05:29:10
【问题描述】:

我正在尝试从网站获取数据并添加到我的 collectionview,但是当我调用 [self.collectionView reloadData] 时出现问题,它不起作用。

所以我的代码如下:

- (void)viewDidLoad {
    [PYBSkuApi getSKUList:1 andHotId:@"17" success:^(NSArray *skuList) {
        self.dataSource = [NSMutableArray arrayWithArray:skuList];
        [self.skuCollectionView reloadData];
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];
}


// Data source 

- (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return [self.dataSource count];
}

- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 1;
}

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

问题是当我重新加载集合视图时,self.dataSource 更新后,它进入

 - (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView

但从不进入

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

我不知道为什么。

【问题讨论】:

  • numberOfSectionsInCollectionView: 返回什么? numberOfItemsInSection 被调用了吗?
  • 是否返回计数?
  • 确保您已连接“Delegate”和“Datasource”以获取集合视图。
  • 是的,它返回 8,我为自己添加了委托和数据源
  • 为什么在numberOfItemsInSection中返回1而不返回[self.dataSource[section] count]; ?

标签: ios objective-c uicollectionview


【解决方案1】:

你有没有调用过 setCollectionViewLayout 或 initWithFrame:collectionViewLayout:

UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[_collectionView setCollectionViewLayout:flowLayout];

_collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];

【讨论】:

    【解决方案2】:

    我遇到了同样的问题(有时UICollectionView 不会在reloadData 之后调用dataSource 的方法)。
    UICollectionView 在layoutSubview 方法中重建列表,如果您在某些dataSource 方法中设置了断点,您就可以知道它。要强制 UICollectionView 重新加载列表,您应该使该集合视图的布局无效:

    <...>
    [self.collectionView reloadData];
    [self.collectionView setNeedsLayout];
    [self.collectionView layoutIfNeeded];
    <...>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多