gpt4 book ai didi

ios - 设置变量值后,打印为未更改

转载 作者:行者123 更新时间:2023-11-29 01:29:11 25 4
gpt4 key购买 nike

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

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

这会更改我的 CounterView 类中 counter 的值。该类看起来像这样:

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,即使我只是将该值设置为不同的数字。

最佳答案

这很简单。

每次编写时都会创建一个 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)
}

关于ios - 设置变量值后,打印为未更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33635149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com