Swift 按顺序绘制多个圆

Swift Draw multiple circles in order

如何在Swift中按顺序绘制多个圆圈,当用户在TextField中输入数字时,我想在左侧视图中绘制圆圈中的数量:

样本:

到目前为止这是我的代码:

func drawCircleInsideView(view: UIView, count: Int){
    let halfSize:CGFloat = min(view.bounds.size.width/2, view.bounds.size.height/2) / CGFloat(count)
    let desiredLineWidth:CGFloat = 1
    var i = 0
    var lastPosition = 0
    while i <= count {
      print(“THIAGO: “, i)
      i = i + 1
      let circlePath = UIBezierPath(
          arcCenter: CGPoint(x:halfSize,y:halfSize),
          radius: CGFloat( halfSize - (desiredLineWidth/2) ),
          startAngle: CGFloat(0),
          endAngle:CGFloat(Double.pi * 2),
          clockwise: true)
      let shapeLayer = CAShapeLayer()
      shapeLayer.path = circlePath.cgPath
      shapeLayer.fillColor = UIColor.green.cgColor
      shapeLayer.strokeColor = UIColor.green.cgColor
      shapeLayer.lineWidth = desiredLineWidth
      view.layer.addSublayer(shapeLayer)
      lastPosition = lastPosition + 2
    }
  }

您需要使用 i .. 来更改圆心

func drawCircleInsideView(view: UIView, count: Int){
      let halfSize:CGFloat = min(view.bounds.size.width/2, view.bounds.size.height/2) / CGFloat(count)
      let desiredLineWidth:CGFloat = 1
      var i = 0
      var lastPosition = 0
      while i <= count {
        print("THIAGO: ", i)
        i = i + 1
        let circlePath = UIBezierPath(
            arcCenter: CGPoint(x:halfSize,y:halfSize + (CGFloat(i) * halfSize*2)),
            radius: CGFloat( halfSize - (desiredLineWidth/2) ),
            startAngle: CGFloat(0),
            endAngle:CGFloat(Double.pi * 2),
            clockwise: true)
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = circlePath.cgPath
        shapeLayer.fillColor = UIColor.green.cgColor
        shapeLayer.strokeColor = UIColor.green.cgColor
        shapeLayer.lineWidth = desiredLineWidth
        view.layer.addSublayer(shapeLayer)
        lastPosition = lastPosition + 2
      }
    }

结果

您可以使用视图和约束:

drawCircles(view: UIView, count: Int) {
    for 0...count {
       let circleView = UIView()

        circleView.layer.cornerRadius = 7.5
        circleView.backgroundColor = UIColor.green
        circleView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(circleView)

        circleView.widthAnchor.constraint(equalToConstant: 15).isActive = true
        circleView.heightAnchor.constraint(equalToConstant: 15).isActive = true
        circleView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true

        circleView.topAnchor.constraint(equalTo: view.topAnchor, constant: topMargin).isActive = true

        topMargin = topMargin + 30.0
    }
}