gpt4 book ai didi

ios - Swift 4,如何有多个拖动和移动 imageView

转载 作者:行者123 更新时间:2023-11-28 14:33:59 24 4
gpt4 key购买 nike

我有一个程序可以使用 UIPanGestureRecognizer 拖动和移动 ImageView。但我想创建另外 3 个 ImageView 对象来做同样的事情。所以不是为每个 UIImageView 创建 4 个 draggedView 函数。我怎么能只有一个,它就可以自动知道我触摸了哪个 ImageView 呢?非常感谢

import UIKit
import Foundation

class ViewController: UIViewController {
@IBOutlet weak var object1: UIImageView!

// Here I want to add another 3 UIImageView as object2,3,4.

@IBOutlet weak var backPanel: UIImageView!
var panGesture1 = UIPanGestureRecognizer()

@objc func draggedView1(_ sender:UIPanGestureRecognizer){
let panelRadius = self.backPanel.frame.size.width/2
self.view.bringSubview(toFront: object1)
let translation = sender.translation(in: self.view)
var newX = object1.center.x + translation.x
var newY = object1.center.y + translation.y
let r = sqrt((newX - backPanel.center.x) * (newX - backPanel.center.x) + (newY - backPanel.center.y) * (newY - backPanel.center.y))
if (r > panelRadius ){
newX = object1.center.x
newY = object1.center.y
}
object1.center = CGPoint(x: newX, y: newY)
sender.setTranslation(CGPoint.zero, in: self.view)
}

override func viewDidLoad() {
super.viewDidLoad()
panGesture1 = UIPanGestureRecognizer(target: self, action: #selector(ViewController.draggedView1(_:)))
backPanel.layer.cornerRadius = self.backPanel.frame.size.width/2
backPanel.layer.masksToBounds = true
object1.layer.cornerRadius = self.object1.frame.size.width/2
object1.layer.masksToBounds = true
object1.isUserInteractionEnabled = true
object1.addGestureRecognizer(panGesture1)
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

最佳答案

UIGestureRecognizerview 属性是它附加到的view。使用它来获取正在移动的 View :

@objc func draggedView1(_ sender:UIPanGestureRecognizer){
guard let object = sender.view else { return }

let panelRadius = self.backPanel.frame.size.width/2
self.view.bringSubview(toFront: object1)
let translation = sender.translation(in: self.view)
var newX = object.center.x + translation.x
var newY = object.center.y + translation.y
let r = sqrt((newX - backPanel.center.x) * (newX - backPanel.center.x) + (newY - backPanel.center.y) * (newY - backPanel.center.y))
if (r > panelRadius ){
newX = object.center.x
newY = object.center.y
}
object.center = CGPoint(x: newX, y: newY)
sender.setTranslation(CGPoint.zero, in: self.view)
}

关于ios - Swift 4,如何有多个拖动和移动 imageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51040375/

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