我在正确显示UICollectionView单元格时遇到问题。我需要在每个偶数索引单元格中显示替代颜色,这非常有效。问题来了,如果我添加另一个单元格,或清除默认设置 - 它们都搞砸了:
我是细胞的子类:
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
override func awakeFromNib() {
super.awakeFromNib()
self.addBtn.contentHorizontalAlignment = .Center
self.addBtn.contentVerticalAlignment = .Center
}
override func drawRect(rect: CGRect) {
//---- Grad Fill
let cell: UICollectionViewCell = txtField.superview!.superview as! UICollectionViewCell
let table: UICollectionView = cell.superview as! UICollectionView
let indexPath = table.indexPathForCell(cell)
// fill every even cell
if (((indexPath?.row)! % 2) == 0) {
let context = UIGraphicsGetCurrentContext()
let space = CGColorSpaceCreateDeviceRGB()
let locations: [CGFloat] = [0.0, 1.0]
let colors = [colorTop, colorBottom]
let gradient = CGGradientCreateWithColors(space, colors, locations)
let startPoint = CGPointMake(0, self.bounds.height)
let endPoint = CGPointMake(self.bounds.width, self.bounds.height)
CGContextDrawLinearGradient(context,gradient,startPoint,endPoint, .DrawsBeforeStartLocation)
}
else{
cell.backgroundColor = UIColor.clearColor()
}
}
然后从按钮操作调用setNeedsDisplay():
self.collectionView.reloadData()
self.collectionView.setNeedsDisplay()
我在这里错过了什么?我确信它是微不足道的......而且,当设备旋转到横向模式时,集合视图不会相应地延伸。我从以下方法调用相同的方法:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
//self.collectionView.frame = CGRectMake(0, 70, self.view.frame.size.width, self.view.frame.size.height - 70)
self.collectionView.setNeedsDisplay()
}
有人可以指出我正确的方向吗?谢谢
答案 0 :(得分:2)
您使用的是错误的方法。根据经验,避免重写drawRect。如果让视图自行绘制,iOS设备上的渲染硬件效率会更高。
而是使用cellForItemAtIndexPath
方法配置您的单元格。根据索引设置背景颜色。始终明确设置背景颜色。不要以为它是以默认颜色开始的,因为对于回收的细胞,它可能不会。
当您添加或删除单元格时,您需要强制整个集合重新加载或编写代码,以确定需要更新哪些单元格,并将reloadItemsAtIndexPaths
消息发送到集合视图,其中包含一个需要重新绘制的细胞。