【发布时间】:2015-03-29 16:09:38
【问题描述】:
在下面的最小示例中,我创建了一个带有五个 UICollectionViewCells 的 UICollectionView。对于每个,我创建一个具有相同frame 的CALayer 并设置其backgroundColor 属性并将其作为子层添加到UICollectionViewCell 的layer 属性。最初在屏幕上的单元格按预期设置,但剩余的单元格可能是错误的颜色,并且在滚动时可能会在完全离开屏幕之前消失。这个问题 [1] 表明这是因为单元格最初不在屏幕上(?),但我没有从答案中看到如何解决问题。
下面是一个最小的工作示例。我尝试过的一些事情被注释掉了:
- 直接设置单元格的背景颜色,以确保这不是我设置集合视图的方式的问题(不是)。
- 调用
setNeedsDisplay()(无效)。 - 删除单元格层的子层(滚动时崩溃)。
import Foundation
import UIKit
enum Colors: Int {
case Red
case Orange
case Yellow
case Green
case Blue
}
class TestViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
var collectionView = UICollectionView(frame: CGRect(x: 100, y: 100, width: 100, height: 100), collectionViewLayout: UICollectionViewFlowLayout())
let reuseIdentifier = "ColorCell"
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.dataSource = self
self.collectionView.delegate = self
self.collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "ColorCell")
self.view.addSubview(self.collectionView)
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(self.reuseIdentifier, forIndexPath: indexPath) as UICollectionViewCell
var l = CALayer()
l.frame = cell.frame
l.delegate = self
if let color = Colors(rawValue: indexPath.item) {
switch color {
case .Red:
l.backgroundColor = UIColor.redColor().CGColor
// cell.backgroundColor = UIColor.redColor()
case .Orange:
l.backgroundColor = UIColor.orangeColor().CGColor
// cell.backgroundColor = UIColor.orangeColor()
case .Yellow:
l.backgroundColor = UIColor.yellowColor().CGColor
// cell.backgroundColor = UIColor.yellowColor()
case .Green:
l.backgroundColor = UIColor.greenColor().CGColor
// cell.backgroundColor = UIColor.greenColor()
case .Blue:
l.backgroundColor = UIColor.blueColor().CGColor
// cell.backgroundColor = UIColor.blueColor()
}
} else {
l.backgroundColor = UIColor.blackColor().CGColor
// cell.backgroundColor = UIColor.redColor()
}
// for sub in cell.layer.sublayers {
// sub.removeFromSuperlayer()
// }
cell.layer.addSublayer(l)
// cell.setNeedsDisplay()
return cell
}
}
【问题讨论】:
标签: ios swift uicollectionview calayer