How to set objects around a circle on a UIView

I wrote code to place objects around a circle, which are located in the center of the user view, but not quite around the circle. I do not know where the code is wrong.

enter image description here

Here is the code:

func createObjectsAroundCircle() { let center = CGPointMake(bounds.width/2 ,bounds.height/2) let radius : CGFloat = 100 let count = 20 var angle = CGFloat(2 * M_PI) let step = CGFloat(2 * M_PI) / CGFloat(count) let circlePath = UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true) let shapeLayer = CAShapeLayer() shapeLayer.path = circlePath.CGPath shapeLayer.fillColor = UIColor.clearColor().CGColor shapeLayer.strokeColor = UIColor.redColor().CGColor shapeLayer.lineWidth = 3.0 self.layer.addSublayer(shapeLayer) // set objects around circle for var index = 0; index < count ; index++ { let x = cos(angle) * radius + center.x let y = sin(angle) * radius + center.y let label = UILabel() label.text = "\(index)" label.frame.origin.x = x label.frame.origin.y = y label.font = UIFont(name: "Arial", size: 20) label.textColor = UIColor.blackColor() label.sizeToFit() self.addSubview(label) angle += step } } 
+8
ios swift
source share
1 answer

Your code is working fine, only the calculation logic is incorrect. You should try setting label.center instead of label.frame.origin or

 let label = UILabel() label.text = "\(index)" label.font = UIFont(name: "Arial", size: 20) label.textColor = UIColor.blackColor() label.sizeToFit() label.frame.origin.x = x - label.frame.midX label.frame.origin.y = y - label.frame.midY 

Remember sizeToFit() before changing the frame or setting the center label. Good luck

+10
source share

All Articles