Search code examples
iosswiftdrawrect

swift drawing shape from class in another viewcontroller (programatically)


I'm in the early stages of making a simple chart. However, I'm having quite some trouble drawing the shape programatically.

I've tried a bunch of variations of this:

let donutChart = CounterView(frame = CGRectMake(100, 100, 100, 100))
cellView.addSubview(donutChart)

There's no errors, but for the past 2 days, I havn't been able to make it draw anything on the screen.

The class I'm attempting to draw is this:

import UIKit

let NoOfGlasses = 8
let π:CGFloat = CGFloat(M_PI)

class CounterView: UIView {

var counter: Int = 5 {
    didSet {
        if counter <=  NoOfGlasses {
            //the view needs to be refreshed
            setNeedsDisplay()
        }
    }
}

var outlineColor: UIColor = UIColor.blueColor()
var counterColor: UIColor = UIColor.orangeColor()

override func drawRect(rect: CGRect) {
    // 1
    let center = CGPoint(x:bounds.width/2, y: bounds.height/2)

    // 2
    let radius: CGFloat = max(bounds.width, bounds.height)

    // 3
    let arcWidth: CGFloat = 76

    // 4
    let startAngle: CGFloat = 3 * π / 4
    let endAngle: CGFloat = π / 4

    // 5
    var path = UIBezierPath(arcCenter: center,
        radius: bounds.width/2 - arcWidth/2,
        startAngle: startAngle,
        endAngle: endAngle,
        clockwise: true)

    // 6
    path.lineWidth = arcWidth
    counterColor.setStroke()
    path.stroke()
}
}

Which should result in this basic shape:

enter image description here

Any help as to how I get this shape drawn in my view controller programatically would be greatly appreciated!


Solution

  • I put your class in a Playground. I was able to get it to draw with the following commands:

    let myview = CounterView()
    myview.frame = CGRectMake(100,100,300,300)
    myview.counter = 5
    

    Here is what it looks like:

    Donut chart in Swift Playground