首页 > 解决方案 > Custom circular progress view in awakeFromNib

问题描述

I have created circle progress view using UIBezierPath and CAShapeLayer with following code.

let center = self.center

let trackLayer = CAShapeLayer()

let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)

trackLayer.path = circularPath.cgPath

trackLayer.strokeColor = UIColor.lightGray.cgColor
trackLayer.lineWidth = 10
trackLayer.fillColor = UIColor.clear.cgColor
trackLayer.lineCap = kCALineCapRound
self.layer.addSublayer(trackLayer)
shapeLayer.path = circularPath.cgPath
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.lineWidth = 10
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineCap = kCALineCapRound
shapeLayer.strokeEnd = 0
self.layer.addSublayer(shapeLayer)
self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))

If I put that code in my viewDidLoad it works fine. However, when I add UIView from storyboard and set its class to custom class then copy all codes to that custom UIView class and call it in awakeFromNib function it is not working what could be the reason? And how can I use above code with custom UIView class?

Orange view should be my custom view I have added leading, trailing, bottom and fixed height constraint it but it looks like above. Does not circle view need to place center of orange view?

标签: iosswiftuiviewuibezierpathcashapelayer

解决方案


Actually it works but it has wrong position. The position in this case is out of your view so you can't see it. It makes you think that your code doesn't work.

If you want to have circle in the center of your view. Put the code in awakeFromNib and calculate center your self, don't use self.center

override func awakeFromNib() {
  let center = CGPoint.init(x: frame.width / 2, y: frame.height / 2)

  let trackLayer = CAShapeLayer()
  let shapeLayer = CAShapeLayer()

  let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)

  trackLayer.path = circularPath.cgPath

  trackLayer.strokeColor = UIColor.lightGray.cgColor
  trackLayer.lineWidth = 10
  trackLayer.fillColor = UIColor.clear.cgColor
  trackLayer.lineCap = kCALineCapRound
  self.layer.addSublayer(trackLayer)
  shapeLayer.path = circularPath.cgPath
  shapeLayer.strokeColor = UIColor.red.cgColor
  shapeLayer.lineWidth = 10
  shapeLayer.fillColor = UIColor.clear.cgColor
  shapeLayer.lineCap = kCALineCapRound
  shapeLayer.strokeEnd = 0
  self.layer.addSublayer(shapeLayer)
}

Result

enter image description here


推荐阅读