UICollectionView - draw a line between cells

强颜欢笑 提交于 2020-01-02 09:55:39

问题


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?


回答1:


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:




回答2:


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.



来源:https://stackoverflow.com/questions/39396778/uicollectionview-draw-a-line-between-cells

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!