如何在UICollectionView加载完成后启动函数?

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomePageTitleCell", for: indexPath) as! HomePageTitleCell cell.news = homePageViewController.sliderList[indexPath.row] let returnleft = IndexPath(row: 0, section: 0) self.collectionView.scrollToItem(at: returnleft, at: UICollectionViewScrollPosition.left, animated: true) return cell } 

如何在加载UICollectionView后使用UICollectionView

 let returnleft = IndexPath(row: 0, section: 0) self.collectionView.scrollToItem(at: returnleft, at: UICollectionViewScrollPosition.left, animated: true) 

不在cellForItemAt工作

cellForItemAt仅用于在表视图中创build单元格。 它将被调用一次为您的表中的每个单元格(不一定一次,但当你滚动到表视图)。

因此,请将代码移到更合适的位置,例如viewDidLoad

 let returnleft = IndexPath(row: 0, section: 0) self.collectionView.scrollToItem(at: returnleft, at:UICollectionViewScrollPosition.left, animated: true)