2017-08-10 101 views
1

我試圖讓這種旋轉機制捕捉直角,當用戶接近(85到95​​度)時,它會自動對齊到90度,直到他離開85度或95度。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

我會打印出你的數學,你會 - 實際上度出來到-180之間... 0 ... 180 ...- 180等 – solenoid

+0

另外,請記住sender.rotation是加法的,這意味着如果你在同一個方向上一堆次,它將是360,720,1080(無論是以rad爲單位)。隨着你走向另一條路,這個數字會降低。 – solenoid

回答

0

數學是不是你正在做的檢查同情(度變量雲:-180 ... 0 ... 180 - > -180 ... 0等)。

另一個問題是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") 
    } 

編輯:https://developer.apple.com/documentation/uikit/uirotationgesturerecognizer/1624337-rotation

+0

你的概念是正確的 – Sayed