gpt4 book ai didi

ios - 如何通过 indexPath 在水平 collectionView 中动态添加 View /图层

转载 作者:搜寻专家 更新时间:2023-10-31 08:24:24 25 4
gpt4 key购买 nike

我正在制作一个带有水平 collectionView 的时间轴,其中对于每个时间 block (一个月),我都有一个单元格,其中包含每天不同颜色的 UIViews。有些月份添加了 30 个 View ,有些是 31 个,有些是 28 个。我无法将 View 动态添加到每个单元格,以免它们被复制或添加到错误的单元格。

为此,我创建了此时间轴的简化版本,其中每个月仅动态添加 1 个图层/ View - 然后我将尝试解决添加可变数量的 View /图层的问题。

我将这个项目作为我正在谈论的最简单的例子:

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 恰好是外边缘,因为有 28 个单元格返回 numberOfItemsInSection 和1 节。所以我想要发生的是除了第 1 和第 28 个单元格 - 浅红色之外,每个单元格都是浅蓝色。

但是,正如您在这里看到的https://imgur.com/a/KTLn7Cb .当我来回滚动时多次填充单元格时,有多种蓝色、红色和紫色阴影,肯定是 1 和 28 以外的那些。

我认为有两个问题。

  1. indexPath.item 以某种方式返回 1 或 28,即使我没有滚动到最边缘的单元格。为什么是这样?
  2. 当我重新访问已经呈现的单元格时,它会重新呈现它们。我不确定这是为什么。我想知道覆盖 prepareForReuse() 是否有帮助,但我听说这通常是个坏主意,所以我不确定它是否是我正在寻找的。

关于实现这一点有什么建议吗?

最佳答案

您忽略了细胞被重复使用的事实。当您更改单元格 fillColor 并且它被滚动关闭时,滚动的单元格会重复使用该单元格,并且您只是将其填充颜色设置为红色,而您没有将其关闭。为每个单元格明确设置 fillColor,无论是红色、白色还是透明色,不要只为选定的单元格设置。

关于ios - 如何通过 indexPath 在水平 collectionView 中动态添加 View /图层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50725727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com