UICollectionView visibleCells returns 无

UICollectionView visibleCells returns nil

虽然显示UICollectionViewCells,但[collectionView visibleCells]returns无。

- (void)viewDidLoad{
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, 320, 568) collectionViewLayout:flowLayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[CustomCell class] forCellWithReuseIdentifier:@"Cell"];
    [self.view addSubview:self.collectionView];

    NSLog(@"%d", [[self.collectionView visibleCells] count]);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    return cell;
}

你有什么想法吗?

在你的视图控制器中试试这个

- (void) viewDidLayoutSubviews {
   NSLog(@"%d", [[self.collectionView visibleCells] count]);
}

该问题是由于重载未完成引起的。 解决方法是: 1. [collectionView重新加载数据]; 2. **[collectionView layoutIfNeeded]; 3. 得到你的 -> [collectionView visibleCells];

尝试添加:

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    collectionView?.collectionViewLayout.invalidateLayout()
}