在nslayout约束上使用uipangesture

问题描述 投票:0回答:1

我下面的快速代码正在使用nslayout约束来加载视图。我试图将uipangestureRecognizer放在imageview上。要使图像视图在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{
        $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)    }




        }
swift uigesturerecognizer nslayoutconstraint swift5 uipangesturerecognizer
1个回答
0
投票

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

将此行添加到viewDidLoad()中:

fight[0].isUserInteractionEnabled = true

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

© www.soinside.com 2019 - 2024. All rights reserved.