微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ios – 如何通过indexPath在水平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,cornerRadius: 5).cgPath
            tickLayer.fillColor = UIColor(red:0.1,blue:0.98,alpha:0.5).cgColor
            cell.layer.addSublayer(tickLayer)
        }
        return cell
    }

}

我们的想法是,对于每个indexPath项(每个单元?),它会查看是否包含在self.filledCells数组中:1或28恰好是外边缘,因为为numberOfItemsInSection和1部分返回了28个单元格.所以我想要发生的是每个细胞都是淡蓝色,除了第一和第二 – 浅红色.

然而,你可以在这里看到https://imgur.com/a/KTLn7Cb.当我来回滚动时,细胞被多次填充,有多种颜色的蓝色,红色和紫色,当然还有1和28以外的颜色.

我认为有两个问题.

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

有关实现这一目标的建议吗

解决方法

你忽视了细胞被重复使用的事实.当你更改一个单元格fillColor,它被滚动关闭时,滚动的单元格重新使用该单元格,你只需将其填充颜色设置为红色,而你没有将其关闭.为每个单元格明确设置fillColor,无论是红色,白色还是透明色,都不要仅为所选单元格设置它.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐