2017-03-21 7 views
2

X 좌표에 따라 ImageView를 회전하려고합니다. 기본적으로 x = 300 일 때 0도 회전하고 x = 190 일 때 180도 회전합니다.UIPanGestureRecognizer-Swift를 사용하여 ImageView를 회전 3

프로그래밍 방식으로 UIPanGestureRecognizer를 프로그래밍해야했습니다. 나는 1가 패닝마다 회전 정도를 변경하려고 거라고하지만 정말 이해가/작동하지 않습니다

@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) 

} 

: 여기 지금 내가 현재 가지고있는 코드입니다. 어떤 도움을 주시면 감사하겠습니다. 정말 고맙습니다!

건배, 테오

+0

당신이 '작동하지 않는'무슨 뜻인지 명확히 할 수 있습니까? – dmorrow

+0

@dmorrow x 좌표에 따라 회전 각도를 변경하는 대신 화면을 가로 질러 imageview를 움직일 때 super가 빠르게 회전합니다. 이 사실이 명확한가요? 감사! –

답변

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

오 세상에 이것은 최고입니다. 소화하고 구현할 시간이 필요합니다. 아픈 지금은 확인 표시를주지! –