我正在制作一个模拟发动机油门的应用程序。当我滑动 UISlider 时,我希望 RPM 量规指针增加并且 RPM 量规内的 UILabel 更新。除了一个奇怪的部分外,我的一切都正常工作:UILabel 中的文本会覆盖自身(即,它会将自身绘制在自身之上,因此所有值都相互叠加并且不可读)。这是我的 ViewController 中的滑块代码:
@IBAction func changeThrottleSetting(sender: UISlider)
{
compactEngineView.RPMPointerAngleInt = Int(sender.value)
compactEngineView.setNeedsDisplay()
}
然后在 compactEngineView 本身:
var RPMPointerAngleInt = Int()
var RPMPointerAngle: CGFloat { //this angle is used to draw the pointer points later down in the code, didn't show it here just to keep it shorter
var AngleCGFloat = CGFloat(RPMPointerAngleInt)
var Pi = CGFloat(M_PI)
var CorrectedAngle = (9 * Pi / 800) * AngleCGFloat - (Pi/2) //just some math to make it look right on the display
return CorrectedAngle
}
var RPMPercentageValue: Int {
var correctedValue = (0.55) * Float(RPMPointerAngleInt) + 55
return Int(correctedValue)
}
override func drawRect(rect: CGRect)
{
let RPMPointerPath = UIBezierPath()
RPMPointerPath.moveToPoint(RPMPointer1)
RPMPointerPath.addLineToPoint(RPMPointer2)
RPMPointerPath.addLineToPoint(RPMPointer3)
RPMPointerPath.addLineToPoint(RPMPointer1)
whiteColor.set()
RPMPointerPath.stroke()
RPMPointerPath.fill()
//here is the troublemaker
let RPMdisplaylabel = UILabel(frame: CGRectMake(0, 0, 81, 32))
RPMdisplaylabel.center = RPMdisplayLocation
RPMdisplaylabel.textAlignment = NSTextAlignment.Right
RPMdisplaylabel.text = "\(RPMPercentageValue)%"
RPMdisplaylabel.textColor = UIColor.whiteColor()
RPMdisplaylabel.font = UIFont(name: "HelveticaNeue",
size: 27.0)
self.addSubview(RPMdisplaylabel)
}
指针完美运行。没什么好抱怨的。但是每次我移动滑块时,文本都会自动覆盖。DrawRect 部分中的 UILabels 有单独的技巧吗?谢谢!