2017-03-21 80 views
2

我想旋轉一個ImageView我取決於它的X座標。基本上,我希望它在x = 300時旋轉0º,當x = 190時旋轉180º。使用UIPanGestureRecognizer旋轉ImageView Swift 3

我不得不以編程方式編程UIPanGestureRecognizer。下面是代碼我現在有現在:

@objc func personDrag(recognizer: UIPanGestureRecognizer) { 

    let rotationSub: CGFloat = 1 

    let translation = recognizer.translation(in: rView) 
    if let view = recognizer.view { 
     view.center = CGPoint(x:view.center.x + translation.x, y:view.center.y + translation.y) 
     view.transform = view.transform.rotated(by: CGFloat.pi - rotationSub) 
    } 
    recognizer.setTranslation(CGPoint.zero, in: rView) 

} 

我會嘗試1每次搖一次改變旋轉程度,但它並沒有真正的工作/有意義。任何幫助,將不勝感激。非常感謝!

乾杯,西奧

+0

你能澄清你說「這是行不通的」是什麼意思? – dmorrow

+0

@dmorrow它只是在屏幕上移動圖像視圖時快速旋轉,而不是根據x座標改變旋轉角度。這是否澄清?謝謝! –

回答

3

可以建立在此的實現:

import UIKit 

class ViewController: UIViewController { 

    @IBOutlet weak var imageview: UIImageView! 

    private var currentRotation: Rotation = .none 

    /* Certain rotation points (rotation of 0º when x = 300 and a rotation of 180º when x = 190) */ 
    enum Rotation { 
     case none, xPoint190, xPoint300 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan)) 
     imageview.addGestureRecognizer(gestureRecognizer) 
     imageview.isUserInteractionEnabled = true 
    } 

    @IBAction func handlePan(_ gestureRecognizer: UIPanGestureRecognizer) { 
     guard gestureRecognizer.state == .began || gestureRecognizer.state == .changed else { 
      return 
     } 

     guard let imgView = gestureRecognizer.view else { 
      return 
     } 

     let translation = gestureRecognizer.translation(in: self.view) 
     imgView.center = CGPoint(x: imgView.center.x + translation.x, y: imgView.center.y + translation.y) 
     gestureRecognizer.setTranslation(CGPoint.zero, in: self.view) 

     let angle: CGFloat = self.degreesToRadians(180.0) 

     /* After reaching x point case - rotating and setting rotation occured to prohibit further rotation */ 

     if imgView.layer.frame.origin.x <= 190, currentRotation != .xPoint190 { 

     imgView.transform = imgView.transform.rotated(by: angle) 
     currentRotation = .xPoint190 

    } else if imgView.layer.frame.origin.x >= 300, currentRotation != .xPoint300 { 

     imgView.transform = imgView.transform.rotated(by: angle) 
     currentRotation = .xPoint300 
    } 


    private func degreesToRadians(_ deg: CGFloat) -> CGFloat { 
     return deg * CGFloat.pi/180 
    } 
} 
+0

我覺得你很困惑。我希望圖像在我拖過屏幕時旋轉。 –

+1

@TheoStrauss編輯了我的答案。實現拖動,當圖像視圖達到它旋轉的某個x點時。希望這是你想要的;] –

+0

哦,我的上帝,這真棒。我需要一些時間來消化和執行,並與你一起生病。生病給你現在的複選標記! –