meowmeowmeow meowmeowmeow - 1 year ago 138
iOS Question

UICollectionView - draw a line between cells

How do I draw a line between cells in a UICollectionView that crosses over the spaces?
The intended output is something like this.:

enter image description here

The best that I've done is to add lines inside each cell. How do I connect the lines through the spaces?

Answer Source

I made an extension that you can use like this:

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()
    ) {
            let fromPoint = cellForItemAtIndexPath(from)?.center,
            let toPoint = cellForItemAtIndexPath(to)?.center
        else {

        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


The result looks like this:

A line drawn from first to second cell

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download