【问题标题】:use uipangesture on a nslayout constraint在 nslayoutconstraint 上使用 uipan 手势
【发布时间】:2020-02-06 03:10:00
【问题描述】:

我下面的 swift 代码在视图中使用 nslayout 约束确实加载了。我试图在图像视图上放置一个 uipangestureRecognizer。让图像视图在 uiview 控制器中移动。现在如果我触摸 imageview 什么都不会发生。我知道我已经在视图中放置了永久约束。我只是不知道如何让图像视图四处移动。我试图移动的图像视图是战斗[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】:

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

    viewDidLoad()中添加这一行:

    fight[0].isUserInteractionEnabled = true
    

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

    【讨论】:

      猜你喜欢
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多