2

我正在尝试为 CollectionView 的可见单元格绘制一个圆圈,如下所示

在此处输入图像描述

我试图让它低谷addSubview,然后removeFromSuperview是以前的标签,但它不起作用

let myIndex1 = IndexPath(row: 0, section: 0)
    let myIndex2 = IndexPath(row: 1, section: 0)
if indexPath.row == 0 {

    collectionView.cellForItem(at:myIndex1)?.addSubview(labelNew)
            labelNew.layer.backgroundColor = selectedItem.title.cgColor

        }

        if indexPath.row == 1 {

            labelNew.removeFromSuperview()
            collectionView.cellForItem(at:myIndex2)?.addSubview(labelNew2)
            labelNew2.layer.backgroundColor = selectedItem.title.cgColor

        }

目前在中心的 CollectionView 单元格周围画一个圆圈的正确方法是什么?

4

1 回答 1

2

对于您正在使用的库。在您的单元格中添加一个背景图像,该图像将显示为与您相同的大小collectionViewhidden默认设置。那么您需要在您的scrollViewDidScroll方法中应用逻辑并显示位于中心的单元格的背景图像,例如:

let indexPath = IndexPath(item: currentIndex, section: 0)
if let cell = wheelMenuCollectionView.cellForItem(at: indexPath) as? WheelMenuCollectionViewCell {
    cell.backImage.isHidden = false
}

并且要删除以前的单元格背景图像,您需要添加

for (index, _) in items.enumerated() {
    if index != currentIndex {
        let oldIndexPath = IndexPath(item: index, section: 0)
        if let cell = wheelMenuCollectionView.cellForItem(at: oldIndexPath) as? WheelMenuCollectionViewCell {
            cell.backImage.isHidden = true
        }
    }
}

你的scrollViewDidScroll方法看起来像:

func scrollViewDidScroll(_ scrollView: UIScrollView) {

    let maxOffset = scrollView.bounds.width - scrollView.contentSize.width
    let maxIndex = CGFloat(self.items.count - 1)
    let offsetIndex = maxOffset / maxIndex

    let currentIndex = Int(round(-scrollView.contentOffset.x / offsetIndex)).clamped(to: (0 ... self.items.count-1))

    if self.items[currentIndex].id != self.selectedItem.id {
        self.selectedItem = self.items[currentIndex]
    }

    let indexPath = IndexPath(item: currentIndex, section: 0)
    if let cell = wheelMenuCollectionView.cellForItem(at: indexPath) as? WheelMenuCollectionViewCell {
        cell.backImage.isHidden = false
    }

    for (index, _) in items.enumerated() {
        if index != currentIndex {
            let oldIndexPath = IndexPath(item: index, section: 0)
            if let cell = wheelMenuCollectionView.cellForItem(at: oldIndexPath) as? WheelMenuCollectionViewCell {
                cell.backImage.isHidden = true
            }
        }
    }
}

现在显示当用户启动您需要添加的应用程序时突出显示的第一个单元格

DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
        let indexPath = IndexPath(item: 0, section: 0)
        if let cell = self.wheelMenuCollectionView.cellForItem(at: indexPath) as? WheelMenuCollectionViewCell {
            cell.backImage.isHidden = false
        }
    })

在你的viewWillAppear方法中。

查看示例项目以获取更多信息。

于 2019-05-05T13:15:10.900 回答