UICollectionView – 在单元格之间绘制一条线

如何在跨越空格的UICollectionView中的单元格之间绘制一条线? 预期的输出是这样的:

在这里输入图像说明

我所做的最好的是在每个单元格内添加行。 如何连接空间的线?

我做了一个扩展,你可以这样使用:

 collectionView.drawLineFrom(indexPathA, to: indexPathB, color: UIColor.greenColor()) 

这里是扩展名:

 extension UICollectionView { func drawLineFrom( from: NSIndexPath, to: NSIndexPath, lineWidth: CGFloat = 2, strokeColor: UIColor = UIColor.blueColor() ) { guard let fromPoint = cellForItemAtIndexPath(from)?.center, let toPoint = cellForItemAtIndexPath(to)?.center else { return } let path = UIBezierPath() path.moveToPoint(convertPoint(fromPoint, toView: self)) path.addLineToPoint(convertPoint(toPoint, toView: self)) let layer = CAShapeLayer() layer.path = path.CGPath layer.lineWidth = lineWidth layer.strokeColor = strokeColor.CGColor self.layer.addSublayer(layer) } } 

结果如下所示:

从第一个到第二个单元格绘制一条线

我可以用下面的代码实现这个,也可以有不同的方法。

好吧,所以我创build了一个自定义UIView自定义frame ,只是盲目地提供frame ,你可以根据你的相邻单元格计算。

  let cell1 = collectionView.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)) let myView = UIView.init(frame: CGRectMake((cell1?.frame.origin.x)!, ((cell1?.frame.origin.y)! + 50.0), (cell1?.frame.size.width)!*4, 10)) myView.backgroundColor = UIColor.blueColor() collectionView.addSubview(myView) collectionView.bringSubviewToFront(myView) 

这将画出一条height 10.0的线。 让我知道这是否有助于你。