Search code examples
swiftuigesturerecognizernslayoutconstraintswift5uipangesturerecognizer

use uipangesture on a nslayout constraint


My swift code below is using nslayout constraints in view did load. I have tried to place a uipangestureRecognizer on a imageview. To get the image view to move around the uiview controller. Right now If I touch the imageview nothing happens. I understand that I have placed permenent constraints in view did load. I just dont know how to get the imageview to move around. The image view I am trying to move is fight[0].

  import UIKit

   class ViewController: UIViewController {

var pic = UIImageView()
var draw = UIView()
let fight = (0..<10).map { _ in UIImageView() }
var g2 = UIPanGestureRecognizer()

override func viewDidLoad() {
    super.viewDidLoad()

    fight[0].image  = UIImage(named: "a.png")



    g2 = UIPanGestureRecognizer(target: self, action: #selector(ViewController.g1Method))
    fight[0].addGestureRecognizer(g2)






    fight.forEach{
        $0.backgroundColor = .clear
        view.addSubview($0)
        $0.translatesAutoresizingMaskIntoConstraints = false
    }


    [pic,draw].forEach{
        $0.backgroundColor = .red
        view.addSubview($0)
        $0.translatesAutoresizingMaskIntoConstraints = false

    }
    // Do any additional setup after loading the view.
    NSLayoutConstraint.activate ([




        fight[0].trailingAnchor.constraint(equalTo: view.trailingAnchor, constant :0),
        fight[0].topAnchor.constraint(equalTo: view.topAnchor, constant : 50),

        fight[0].heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.10, constant: 0),
        fight[0].widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.10, constant: 0),
        fight[0].leadingAnchor.constraint(equalTo: view.leadingAnchor, constant : 0),




    ])


}

@objc func g1Method(_ sender: UIPanGestureRecognizer){


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




        }

Solution

  • By default, UIImageView do not have user interaction enabled.

    Add this line inside viewDidLoad():

    fight[0].isUserInteractionEnabled = true
    

    You should now be able to drag that image view around.