繁体   English   中英

UICollectionView - 在单元格之间画一条线

[英]UICollectionView - draw a line between cells

如何在跨越空间的 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)
    }
}

结果如下所示:

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

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

好的,所以我正在创建一个带有自定义frame的自定义UIView并且只是盲目地提供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的线。 如果这对您有帮助,请告诉我。

更新了@Callam 对 Swift 5 的回答并添加了一些小的修改

  • 使用dequeueReusableCell代替cellForItemAtIndexPath
  • 使用您需要在其他地方创建的自定义集合视图单元格。 您还需要为其指定一个重用标识符名称。
extension UICollectionView {

    func drawLineFrom(
        from: IndexPath,
        to: IndexPath,
        lineWidth: CGFloat = 2,
        strokeColor: UIColor = UIColor.blue
    ) {
        
        let fromPoint = self.dequeueReusableCell(withReuseIdentifier: "fooReuseIdentifier", for: from) as? FooCustomCollectionViewCell
        let toPoint = self.dequeueReusableCell(withReuseIdentifier: "fooReuseIdentifier", for: to) as? FooCustomCollectionViewCell

        let path = UIBezierPath()

        guard let fromCenter = fromPoint?.center else { return }
        guard let toCenter = toPoint?.center else { return }

        path.move(to: convert(fromCenter, to: self))
        path.addLine(to: convert(toCenter, to: self))

        let layer = CAShapeLayer()

        layer.path = path.cgPath
        layer.lineWidth = lineWidth
        layer.strokeColor = strokeColor.cgColor

        self.layer.addSublayer(layer)
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM