我遵循教程here,该教程演示了如何实现自定义UIControl。但是,我想停止自定义控件无休止地旋转。我已经能够阻碍旋转旋钮的能力但却无法创造明确的停止点。
我的尝试
在下面的代码中我使用了作者angle
变量,范围从0到360.逻辑有点不稳定,但我
override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
super.continueTrackingWithTouch(touch, withEvent: event)
if (angle <= 1) {
angle = 2
return false
} else if angle >= 356 {
angle = 355
return false
} else {
let lastPoint = touch.locationInView(self)
self.moveHandle(lastPoint)
self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
return true
}
}
注意:我已经尝试了所有明显的操作符和逻辑。我觉得这完全是错误的做法。
结果
基本上,控制动作将停在1,但前提是我移动缓慢。如果我快速拖动旋钮,它会旋转到1,让控件无限旋转。
如何正确限制UIControls的运动范围从1到355?
我已经整理了一个可以下载和测试的简单工作项目。
答案 0 :(得分:1)
将continueTrackingWithTouch
更改为:
// Part of UIControl, used to track user input
override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
let lastPoint = touch.locationInView(self)
self.moveHandle(lastPoint)
return super.continueTrackingWithTouch(touch, withEvent: event)
}
将moveHandle
更改为:
func moveHandle(lastPoint:CGPoint){
let threshholdAngle = 180
let centerPoint:CGPoint = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2)
let currentAngle:Double = AngleFromNorth(centerPoint, p2: lastPoint, flipped: false)
let angleInt = Int(floor(currentAngle))
let newAngle = Int(360 - angleInt)
if abs(newAngle - angle) > threshholdAngle {
return
}
//Store the new angle
angle = newAngle
sendActionsForControlEvents(UIControlEvents.ValueChanged)
//Update the textfield
//textField!.text = "\(angle)"
//Redraw
setNeedsDisplay()
}