所以我正在创建一个集合视图,在每个单元格的滚动上,集合视图的背景将更改为我所拥有的图像。问题是bg甚至在单元格出现在视图中之前就发生了更改。我该如何解决这个问题?
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! HomeCollectionViewCell
cell.cellNavTitle.text = appConfig.menuItems[indexPath.row]
cell.cellNavImage.image = UIImage(named: (appConfig.icon[indexPath.row]))
cell.cellNavDescription.text = appConfig.title[indexPath.row]
switch indexPath.row{
case 0:
collectionView.backgroundColor = UIColor(patternImage: UIImage(named: "1414441938milaj_bg2")!)
break
case 1:
collectionView.backgroundColor = UIColor.blueColor()
break
case 2:
collectionView.backgroundColor = UIColor.grayColor()
break
default:
break
}
return cell
}
如果matthias方法不起作用,请尝试使用滚动代理。在那里,您可以设置所需的确切高度,并根据需要更改背景。试试这个:-把你的逻辑置于If条件下。在这里,我只是设置了一个逻辑来检查滚动高度。
func scrollViewDidScroll(scrollView: UIScrollView) {
let contentOffset: CGFloat = scrollView.contentOffset.y
if contentOffset < 500 {
collectionView.backgroundColor = UIColor(patternImage: UIImage(named: "1414441938milaj_bg2")!)
} else if contentOffset < 700 {
collectionView.backgroundColor = UIColor.blueColor()
} else if contentOffset < 900 {
collectionView.backgroundColor = UIColor.grayColor()
}
}
更改contentOffset值根据您的收藏视图高度
您可以尝试使用此委托:
optional func collectionView(_ collectionView: UICollectionView,
willDisplayCell cell: UICollectionViewCell,
forItemAtIndexPath indexPath: NSIndexPath)
集合视图在将单元格添加到其所容纳之物使用此方法检测单元格添加,而不是监视细胞本身以查看它何时出现。
即
func collectionView(collectionView: UICollectionView,
willDisplayCell cell: UICollectionViewCell,
forItemAtIndexPath indexPath: NSIndexPath) {
switch indexPath.row{
case 0:
collectionView.backgroundColor = UIColor(patternImage: UIImage(named: "1414441938milaj_bg2")!)
break
case 1:
collectionView.backgroundColor = UIColor.blueColor()
break
case 2:
collectionView.backgroundColor = UIColor.grayColor()
break
default:
break
}
}