使用新实例的值更新视图

时间:2015-11-10 18:00:25

标签: ios swift charts instance

我正在尝试使用新值更新图表。我可以创建一个新的类实例,但我不知道如何更新视图以反映新实例的值。

我的图表类:

import UIKit

@IBDesignable class CounterView: UIView {

    let possiblePoints = 100
    let π:CGFloat = CGFloat(M_PI)

    var counter: Int = 20
    @IBInspectable var outlineColor: UIColor = UIColor.blueColor()
    @IBInspectable 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: radius/2 - arcWidth/2,
            startAngle: startAngle,
            endAngle: endAngle,
            clockwise: true)

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

        //Draw the outline

        //1 - first calculate the difference between the two angles
        //ensuring it is positive
        let angleDifference: CGFloat = 2 * π - startAngle + endAngle

        //then calculate the arc for each single glass
        let arcLengthPerPoint = angleDifference / CGFloat(possiblePoints)

        //then multiply out by the actual glasses drunk
        let outlineEndAngle = arcLengthPerPoint * CGFloat(counter) + startAngle

        //2 - draw the outer arc
        var outlinePath = UIBezierPath(arcCenter: center,
            radius: bounds.width/2 - 2.5,
            startAngle: startAngle,
            endAngle: outlineEndAngle,
            clockwise: true)

        //3 - draw the inner arc
        outlinePath.addArcWithCenter(center,
            radius: bounds.width/2 - arcWidth + 2.5,
            startAngle: outlineEndAngle,
            endAngle: startAngle,
            clockwise: false)

        //4 - close the path
        outlinePath.closePath()

        outlineColor.setStroke()
        outlinePath.lineWidth = 5.0
        outlinePath.stroke()
    }
}

默认情况下,counter的值为20,但我需要更新UIView以反映新CounterView()实例的值。我传入的分数在以下函数中为50:

我的ViewController:

@IBOutlet weak var chart: CounterView!

func scoreDisplay(score:Double) {
    let counterView = CounterView()
    counterView.counter = Int(score)
    print(counterView.counter)
    chart = counterView
    chart.counter = counterView.counter
    chart.setNeedsDisplay()
}

这会将chart.counter的值设置为50的正确值,而不是默认值20,但我需要重新绘制图表,{{1}似乎无法正常工作。

0 个答案:

没有答案