My code declares 2 different @objc func methods using UIPan gestureRecongnizzer. I would think there would be a way to use just 1 objc func method using a tag. All the function currently does is move the imageview around. I dont know if tag is the best way and I am open to other solutions I just want 1 func. Specifically look at pgGestureMethod and sgGestureMethod.
var pg = UIImageView()
var pgGesture = UIPanGestureRecognizer()
var pgCon = [NSLayoutConstraint]()
var sg = UIImageView()
var sgGesture = UIPanGestureRecognizer()
var sgCon = [NSLayoutConstraint]()
override func viewDidLoad() {
super.viewDidLoad()
[pg,sg].forEach({
$0.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview($0)
$0.isUserInteractionEnabled = true
})
pgGesture = UIPanGestureRecognizer(target: self, action: #selector(ViewController.pgGestureMethod(_:)))
pg.addGestureRecognizer(pgGesture)
sgGesture = UIPanGestureRecognizer(target: self, action: #selector(ViewController.sgGestureMethod(_:)))
sg.addGestureRecognizer(sgGesture)
}
@objc func pgGestureMethod(_ sender: UIPanGestureRecognizer){
self.view.bringSubviewToFront(pg)
let tranistioon = sender.translation(in: self.view)
pg.center = CGPoint(x: pg.center.x + tranistioon.x, y: pg.center.y + tranistioon.y)
sender.setTranslation(CGPoint.zero,in: self.view)
}
@objc func sgGestureMethod(_ sender: UIPanGestureRecognizer){
let tranistioon = sender.translation(in: self.view)
sg.center = CGPoint(x: sg.center.x + tranistioon.x, y: sg.center.y + tranistioon.y)
sender.setTranslation(CGPoint.zero,in: self.view)
}
Gesture recognisers have a view
property that refers to the view to which they are added, so you don't even need a tag!
Just use one single action method like this:
@objc func pgGestureMethod(_ sender: UIPanGestureRecognizer){
// I replaced every "pg" with "sender.view!"
self.view.bringSubviewToFront(sender.view!)
let tranistioon = sender.translation(in: self.view)
sender.view!.center = CGPoint(x: sender.view!.center.x + tranistioon.x, y: sender.view!.center.y + tranistioon.y)
sender.setTranslation(CGPoint.zero,in: self.view)
}
If not writing self.view.bringSubviewToFront(sg)
is actually intentional, you can simply check sender.view!
:
@objc func pgGestureMethod(_ sender: UIPanGestureRecognizer){
if sender.view == pg {
self.view.bringSubviewToFront(pg)
}
let tranistioon = sender.translation(in: self.view)
sender.view!.center = CGPoint(x: sender.view!.center.x + tranistioon.x, y: sender.view!.center.y + tranistioon.y)
sender.setTranslation(CGPoint.zero,in: self.view)
}