gpt4 book ai didi

swift - 在 nslayout 约束上使用 uipangesture

转载 作者:行者123 更新时间:2023-11-30 10:25:22 26 4
gpt4 key购买 nike

下面我的 swift 代码在 View 加载时使用 nslayout 约束。我尝试在 ImageView 上放置一个 uipangestureRecognizer 。使 ImageView 在 uiview Controller 中移动。现在,如果我触摸 ImageView ,什么也不会发生。我知道我已经对 View 的加载设置了永久约束。我只是不知道如何让 ImageView 移动。我试图移动的 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) }




}

最佳答案

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

viewDidLoad() 中添加此行:

fight[0].isUserInteractionEnabled = true

您现在应该能够拖动该 ImageView 。

关于swift - 在 nslayout 约束上使用 uipangesture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60087162/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com