How do I draw a line between cells in a UICollectionView that crosses over the spaces? The intended output is something like this.:
The best that I've done is to add lines inside each cell. How do I connect the lines through the spaces?
How do I draw a line between cells in a UICollectionView that crosses over the spaces? The intended output is something like this.:
The best that I've done is to add lines inside each cell. How do I connect the lines through the spaces?
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()
) {
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 looks like this:
I could achieve this with below code, might have different approach too.
Ok, so I am creating a custom UIView
with custom frame
and just providing the frame
blindly, you can calculate based on your adjacent 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)
This would draw a line of height 10.0
. Let me know if this helps you.