2017-08-10 5 views
1

私はこの回転機構を直角にスナップしようとしています。ユーザーが近づくと(85〜95度)、彼は85度または95度から離れるまで自動的に90度にスナップします。直角にスナップするUIRotationGestureRecognizer

var lastRotation = CGFloat() 
func rotateAction(sender:UIRotationGestureRecognizer){ 


    let currentTransform = sender.view?.transform 
    let rotation = 0.0 - (lastRotation - sender.rotation) 
    let newTransform = currentTransform!.rotated(by: rotation) 

    let radians = atan2f(Float(sender.view!.transform.b), Float(sender.view!.transform.a)) 
    let degrees = radians * (180/.pi) 

    sender.view?.transform = newTransform 
    lastRotation = sender.rotation 
    if sender.state == .ended { 
     lastRotation = 0.0; 
    } 

    // The if statement works correctly when reaching the angles 
    if degrees > -95 && degrees < -85 { 

    } 
    else if degrees > -185 && degrees < -175 { 

    } 
    else if degrees > -275 && degrees < -265 { 

    } 
    else if degrees > -5 && degrees < 5 { 
     // So I tried this but it does not seem right, it always pushed it away from angle 0 
     lastRotation = CGFloat(0.0 - radians) 
    } 

} 
+0

- 度が実際に0 ... -180の間に出てくる... 180 ...- 180など – solenoid

+0

また、維持あなたが同じ方向に何度も回っていくと、それは360、720、1080(それがラジアンであるものであれ)になります。あなたが他の方向に進むと、その数は少なくなります。 – solenoid

答えて

0

数学は(: - 等...> -180 0 -180 ... 0 ... 180度変数が行く)あなたがやっているのを確認して同情ではありません。

もう1つの問題は、sender.rotationが累積的であることです。つまり、回転しながらradを加算または減算し続けることになります。

もう一度数式を修正したら、「スナップ」をチェックするために次のようなことをお勧めします。

let rad = fabs(sender.rotation.truncatingRemainder(dividingBy: 2 * CGFloat.pi)) 

    print("rotation", sender.rotation, degrees, rad) 

    switch rad { 
    case 1.48353...1.65806 : 
     print("do things") 
    case 3.05433...3.22886 : 
     print("do things") 
    case 4.62512...4.79966 : 
     print("do things") 
    case 0...0.0872665 : 
     print("this is check one of 2") 
    case 6.19592...6.28319 : 
     print("this is check two of 2") 
    default: 
     print("do other things") 
    } 

EDIT:あなたが行くように私はあなたの数学をプリントアウトでしょうhttps://developer.apple.com/documentation/uikit/uirotationgesturerecognizer/1624337-rotation

+0

あなたのコンセプトは正しいです – Sayed

関連する問題