如何限制自定义UIControl旋钮的运动范围?

时间:2016-02-24 06:01:34

标签: swift uicontrol

我遵循教程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
        }
    }

view code on github

注意:我已经尝试了所有明显的操作符和逻辑。我觉得这完全是错误的做法。

结果

基本上,控制动作停在1,但前提是我移动缓慢。如果我快速拖动旋钮,它会旋转到1,让控件无限旋转。

问题

如何正确限制UIControls的运动范围从1到355?

我已经整理了一个可以下载和测试的简单工作项目。

project files

1 个答案:

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