我有一个很棒的条形图类,使用我自己的Core Graphics代码在应用程序中工作,并在游乐场玩它我注意到drawRect似乎被调用很多次,当没有任何变化时(我'我在下面简要介绍了我的代码,但这是要点。
我注意到,如果我将轴绘图代码放在一个方法中,然后调用该代码的确切位置,那么操场会运行drawRect数千次,直到崩溃程序为止。如果我有它如何显示如下,它只运行一次。
class BarGraphView: UIView {
var frameWidth = CGFloat(0.0)
var frameHeight = CGFloat(0.0)
var values = [CGFloat]()
var maxY = CGFloat(0.0)
var title = NSString(string: "")
var xLabel = NSString(string: "")
let gridOffSetY = CGFloat(0.1)
var xaxis : CGFloat {
return 0.6*frameWidth
}
var yaxis : CGFloat {
return 0.6*frameWidth
}
var xstart : CGFloat {
return 0.2*frameWidth
}
var ystart : CGFloat {
return 0.3*frameWidth
}
var xseparation: CGFloat {
return CGFloat(xaxis*0.05)
}
init(frame: CGRect, data: [CGFloat], maxYVal: Int, title: String, xLabel: String) {
super.init(frame: frame)
frameWidth = frame.width
frameHeight = frame.height
values = data
maxY = CGFloat(maxYVal)
self.title = title as NSString
self.xLabel = xLabel as NSString
}
override func drawRect(rect: CGRect) {
let numValues = CGFloat(values.count)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor);
CGContextFillRect(context, bounds);
CGContextSetFillColorWithColor(context, UIColor.greenColor().CGColor)
let barWidth:CGFloat = ((xaxis-(numValues+1)*xseparation)/numValues)
var count:CGFloat = 0
for number in values {
let x = xstart + xseparation + (count * (barWidth + xseparation))
let barRect = CGRect(x: x, y:ystart+yaxis, width: barWidth, height: -(number/maxY)*yaxis)
CGContextAddRect(context, barRect)
count++
}
CGContextFillPath(context)
// IF THIS CODE IS HERE, IT IS RUN ONCE IN PLAYGROUND
// Axis Drawing
var bezier = UIBezierPath()
// Draw y-axis
bezier.moveToPoint(CGPointMake(xstart,ystart))
bezier.addLineToPoint(CGPointMake(xstart,ystart+yaxis+5))
// Draw x-axis
bezier.moveToPoint(CGPointMake(xstart-5,ystart+yaxis))
bezier.addLineToPoint(CGPointMake(xstart+xaxis,ystart+yaxis))
// Draw value markings on y-axis
let divisor = CGFloat((yaxis-gridOffSetY)/maxY) // max y-value, with offset
for i in 1..<maxY {
bezier.moveToPoint(CGPointMake(xstart-CGFloat(2.5),ystart+gridOffSetY+CGFloat(i)*divisor))
bezier.addLineToPoint(CGPointMake(xstart,ystart+gridOffSetY+CGFloat(i)*divisor))
}
UIColor.blackColor().setStroke()
bezier.stroke()
// IF PUT THAT ^ in this method, it runs thousands of times consecutively, crashing Xcode.
//drawAxis()
}
这看起来像是潜在的错误行为,游乐场是不是很奇怪,或者对此有任何合理的解释?