设置变量值后,它将打印为未更改

时间:2015-11-10 16:45:21

标签: ios swift null counter

我用这个函数改变变量的值:

func scoreDisplay(score:Double) {
    print(score)
    CounterView().counter = Int(score)
    print(CounterView().counter)
}

这会更改counter课程中CounterView的值。该课程如下:

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()
    }
}

分数正确传递,并打印正确的值 - 问题是,只要我更改CounterView().counter的值,我会尝试将其打印出来,但它会返回20即使我只是将值设置为不同的数字。

2 个答案:

答案 0 :(得分:1)

非常简单。

每次编写

时都会创建CounterView的新实例
CounterView()

所以,使用你的代码

CounterView().counter = Int(score)
print(CounterView().counter)

您已创建了2个CounterView个实例。在新创建的print上调用CounterView函数,因此其counter值是您在实现中设置的默认值:20。您需要将实例存储在本地变量中。例如,您的方法可能如下所示

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

答案 1 :(得分:0)

此表达式

CounterView().counter

每次调用CounterView时都会创建一个新实例。

您应该创建一个实例,将其保存在变量中并从该实例访问counter