How to center the text in the middle of a circle?

I made a circle class, but I want to put the text in a straight center.

The font size should not matter, the text should always be displayed in the center.

So far, I just tried arbitrary values ​​until it is close enough to the center. There should be an easier way.

import UIKit class CircleView: UIView { let circleLayer: CAShapeLayer = CAShapeLayer() init(frame: CGRect, innerColor: CGColor = Colors.colorWithHexString("#858585").CGColor, rimColor: CGColor = UIColor.blueColor().CGColor) { super.init(frame: frame) self.backgroundColor = UIColor.clearColor() let circlePath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: (frame.size.width - 10)/2, startAngle: 0.0, endAngle: CGFloat(M_PI * 2.0), clockwise: true) // Setup the CAShapeLayer circleLayer.path = circlePath.CGPath circleLayer.fillColor = innerColor circleLayer.strokeColor = rimColor circleLayer.lineWidth = 5.0 // Don't draw the circle at start circleLayer.strokeEnd = 1.0 layer.addSublayer(circleLayer) } func animateCircle(duration: NSTimeInterval) { let animation = CABasicAnimation(keyPath: "strokeEnd") animation.duration = duration animation.fromValue = 0 animation.toValue = 1 // Do a linear animation animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) circleLayer.strokeEnd = 1.0 // Do the actual animation circleLayer.addAnimation(animation, forKey: "animateCircle") } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } 
+4
source share
1 answer

Assuming you have a UILabel property in your view named label ; you can set the center value to the center of your view in the layoutSubviews method:

 override func layoutSubviews() { super.layoutSubviews() label.sizeToFit() label.center = self.convertPoint(self.center, fromView: self.superview) } 

Please note that with Auto Layout this is much simpler, but you will not be able to change any frame or center as described above:

 self.addConstraint(NSLayoutConstraint( item: label, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0.0)) self.addConstraint(NSLayoutConstraint( item: label, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0)) 
+3
source

All Articles