Установите метку круга для отдельной ячейки CollectionView [Swift] - PullRequest
2 голосов
/ 05 мая 2019

Я пытаюсь нарисовать круг для видимой ячейки CollectionView, выглядит так

enter image description here

Я попытался сделать это через 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, которая в данный момент находится в центре?

1 Ответ

2 голосов
/ 05 мая 2019

Для библиотеки , которую вы используете.Добавьте фоновое изображение в ячейку, размер которого будет соответствовать вашему collectionView, и установите по умолчанию hidden.затем вам нужно применить логику в вашем методе 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 method.

Проверьте THIS пример проекта для получения дополнительной информации.

...