【发布时间】:2018-06-06 16:54:58
【问题描述】:
我正在使用水平 collectionView 制作各种时间线,其中对于每个时间段(一个月),我都有一个单元格,其中包含不同颜色的 UIViews。有些月份添加了 30 个视图,有些是 31,有些是 28。我无法动态地将视图添加到每个单元格,这样它们就不会被复制或添加到错误的单元格中。
为此,我创建了此时间线的简化版本,其中每个月仅动态添加 1 个图层/视图 - 然后我将尝试解决添加可变数量的视图/图层的问题。
我把这个项目作为我所说的最简单的例子:
https://github.com/AlexMarshall12/testTimeline-iOS
这是 ViewController.swift 中的代码:
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var filledCells: [Int] = []
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.filledCells = [1,28]
collectionView.delegate = self
collectionView.dataSource = self
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 28
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! MyCollectionViewCell
print(indexPath.item)
cell.myLabel.text = String(indexPath.item)
if filledCells.contains(indexPath.item) {
let tickLayer = CAShapeLayer()
tickLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: cell.layer.bounds.width, height: cell.layer.bounds.height), cornerRadius: 5).cgPath
tickLayer.fillColor = UIColor(red:0.99, green:0.13, blue:0.25, alpha:0.5).cgColor
cell.layer.addSublayer(tickLayer)
} else {
//updated
let tickLayer = CAShapeLayer()
tickLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: cell.layer.bounds.width, height: cell.layer.bounds.height), cornerRadius: 5).cgPath
tickLayer.fillColor = UIColor(red:0.1, green:0.13, blue:0.98, alpha:0.5).cgColor
cell.layer.addSublayer(tickLayer)
}
return cell
}
}
这个想法是,对于每个 indexPath 项目(每个单元格?),它会查看它是否包含在 self.filledCells 数组中:1 或 28 恰好是外边缘,因为 numberOfItemsInSection 返回了 28 个单元格和1节。所以我想要发生的是每个单元格都是浅蓝色的,除了第 1 个和第 28 个 - 浅红色。
但是,您可以在此处看到 https://imgur.com/a/KTLn7Cb。当我来回滚动时,单元格被多次填充,有多种蓝色、红色和紫色阴影,当然不是 1 和 28。
我认为有两个问题。
- 即使我没有滚动到最边缘的单元格,indexPath.item 也会以某种方式返回 1 或 28。为什么是这样?
- 当我重新访问已渲染的单元格时,它会重新渲染它们。我不确定这是为什么。我想知道重写 prepareForReuse() 是否有帮助,但我听说这通常是个坏主意,所以我不确定它是否是我要找的。
对实现这一目标有什么建议吗?
【问题讨论】:
-
你能更新 GitHub 项目吗?里面什么都没有
标签: ios swift uicollectionview uicollectionviewcell