[英]UICollectionView - draw a line between cells
我做了一个扩展,你可以这样使用:
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.