在 nslayout 约束上使用 uipangesture

use uipangesture on a nslayout constraint

我的 swift 下面的代码在视图中使用 nslayout 约束进行加载。我试图在图像视图上放置一个 uipangestureRecognizer。使图像视图在 uiview 控制器周围移动。现在,如果我触摸图像视图,什么也不会发生。我知道我已经在视图中放置了永久性约束。我只是不知道如何让 imageview 移动。我要移动的图像视图是 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{
        [=10=].backgroundColor = .clear
        view.addSubview([=10=])
        [=10=].translatesAutoresizingMaskIntoConstraints = false
    }


    [pic,draw].forEach{
        [=10=].backgroundColor = .red
        view.addSubview([=10=])
        [=10=].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)    }




        }

默认情况下,UIImageView启用用户交互。

viewDidLoad()里面添加这一行:

fight[0].isUserInteractionEnabled = true

您现在应该可以拖动该图像视图了。