Theo Strauss Theo Strauss -4 years ago 92
iOS Question

Rotating ImageView with UIPanGestureRecognizer, ERROR-- Swift

I am trying to rotate an imageview with a pangesturerecognizer. Basically, I rotate the image depending on the x coordinate. I'm almost there, but I ran into a couple errors.

I set up the gesture recognizer by doing this (i have to do everything programmatically):

let personDrag = UIPanGestureRecognizer(target: self, action: #selector(foo.personDragRecognizer))

rPersonImageView.isUserInteractionEnabled = true
rPersonImageView.addGestureRecognizer(personDrag)
self.fooVarTap6 = personDrag //the class is called foo


And then here is the gesture recognizer function:

@objc func personDragRecognizer(_ gestureRecognizer: UIPanGestureRecognizer) {

guard personDrag.state == .began || personDrag.state == .changed else {
return
}

guard let imgView = personDrag.view else {
return
}

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

//originally had self before .degreesToRadians
let angle: CGFloat = rPersonImageView.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
}

}


Everywhere I mention personDrag it says "use of unresolved identifier personDrag" but I defined personDrag as you can see. It also says that "UIImageView has no member degreesToRadian" but someone else on stack said it should. Can anyone help me with this? Any help would be immensely appreciated!! Thanks a ton in advance.

Cheers,
Theo

Answer Source

personDrag is defined to be a gesture recognizer, assigned properly, and properly coded. But inside your personDragRecognizer() as defined, every reference to should be against gestureRecognizer instead.

The easiest fix to make things work is rename the function as:

func personDragRecognizer(_ personDrag UIPanGestureRecognizer) {
    // your code here
}

The other fix is to rename each and every reference inside as:

guard gestureRecognizer.state == .began || gestureRecognizer.state == .changed else {
    return
}

So on and so forth.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download