UICollectionView - draw a line between cells

How to draw a line between cells in a UICollectionView that intersects spaces? The expected result looks something like this:

enter image description here

The best I have done is add rows inside each cell. How to connect lines with spaces?

0
source share
2 answers

I made an extension that you can use as follows:

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

Here is the extension:

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)
    }
}

The result is as follows:

Row taken from the first to second cell

+1
source

I could achieve this using the code below, may also have a different approach.

So, I create a custom one UIViewwith a custom one frameand just keep track of what frameyou can count based on your neighboring cells.

    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. , .

+1

All Articles