TIMEX TIMEX - 9 months ago 59
Swift Question

How do I draw a circle in iOS Swift?

let block = UIView(frame: CGRectMake(cellWidth-25, cellHeight/2-8, 16, 16))
block.backgroundColor = UIColor(netHex: 0xff3b30)
block.layer.cornerRadius = 9
block.clipsToBounds = true

This is what I have right now, but it's obviously not the right way to do it.

What's the simplest way to do it?


You can draw a circle with this:

    let circlePath = UIBezierPath(arcCenter: CGPoint(x: 100,y: 100), radius: CGFloat(20), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = circlePath.CGPath

    //change the fill color
    shapeLayer.fillColor = UIColor.clearColor().CGColor
    //you can change the stroke color
    shapeLayer.strokeColor = UIColor.redColor().CGColor
    //you can change the line width
    shapeLayer.lineWidth = 3.0


With the code you have posted you are cropping the corners of the UIView, not adding a circle to the view.

If you have a UIView (which is square, and which is say red in Storyboard) and you simply want to turn it in to a red circle, just do this

// It makes a UIView into a circular dot of color
import UIKit
class Dot:UIView
    override func layoutSubviews()
        { layer.cornerRadius = bounds.size.width/2; }