调整我的UIView CAShapeLayer中心

时间:2018-03-04 12:48:19

标签: ios cashapelayer

我几天都试图解决这个问题,而且这些建议都没有解决我的问题。我在UIView内有一个UITableView。我一直试图在我的CAShapeLayer内画出UIView,但我无法做到正确。

我需要黄色CAShapeLayer正好位于灰色UIView内。

func DrawActivityRect(cell: CalorieDashboardTVCell){
    let rectangle = UIBezierPath(rect: cell.calorieBurnUIView.bounds)

    let trackLayer = CAShapeLayer()
    trackLayer.frame = cell.calorieBurnUIView.bounds
    trackLayer.path = rectangle.cgPath
    trackLayer.position = cell.calorieBurnUIView.center
    trackLayer.strokeColor = UIColor.yellow.cgColor
    trackLayer.lineWidth = 10
    trackLayer.fillColor = UIColor.clear.cgColor
    trackLayer.lineCap = kCALineCapRound
    cell.calorieBurnUIView.layer.addSublayer(trackLayer)
}

结果: enter image description here

1 个答案:

答案 0 :(得分:0)

我怀疑在设置图层后单元格大小会发生变化。最简单的解决方法是在单元格的layoutSubviews()中。由于您的路径使用绝对坐标,因此您需要更新图层框架和路径。

override func layoutSubviews() {
    super.layoutSubviews()

    // You need to keep trackLayer around after you created it
    let rectangle = UIBezierPath(rect: cell.calorieBurnUIView.bounds)
    self.trackLayer.frame = cell.calorieBurnUIView.bounds
    self.trackLayer.path = rectangle.cgPath
    self.trackLayer.position = cell.calorieBurnUIView.center
}