我试图为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单元周围绘制圆的正确方法是什么?
答案 0 :(得分:2)
对于您使用的library。在您的单元格中添加一个背景图片,该图片的大小将与您的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
方法。
检查THIS示例项目以了解更多信息。