嘿伙计们我刚刚创建了一个可以在视图中拖动的示例图像视图。
我的问题是如何在拖动图像并将其放入删除图标时删除图像?
任何人都可以使用快速代码
在此我附上了我的示例程序代码:
import UIKit
class ViewController: UIViewController, UIGestureRecognizerDelegate {
var Lastscale : CGFloat = 1.0
@IBOutlet weak var imgView: UIImageView!
@IBOutlet weak var deleteIcon: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(ViewController.handlePan(recognizer:)))
panGestureRecognizer.delegate = self
imgView.addGestureRecognizer(panGestureRecognizer)
imgView.isUserInteractionEnabled = true
}
@objc func handlePan(recognizer: UIPanGestureRecognizer) {
let gview = recognizer.view
if recognizer.state == .began || recognizer.state == .changed {
let translation = recognizer.translation(in: gview?.superview)
gview?.center = CGPoint(x: (gview?.center.x)! + translation.x, y: (gview?.center.y)! + translation.y)
recognizer.setTranslation(CGPoint.zero, in: gview?.superview)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:1)
首先,使用switch语句来检查识别器状态是否更清晰。此外,我认为在这种情况下,您希望在识别器转换发生变化时设置图层的变换,这样您就可以保留视图的初始帧,并始终可以通过将变换设置为其标识来设置动画。然后,如果按钮和图像视图层的矩形相交,则隐藏imageView,否则返回。像这样:
@objc func handlePan(recognizer: UIPanGestureRecognizer) {
let gview = recognizer.view
let translation = recognizer.translation(in: gview?.superview)
switch recognizer.state {
case .began, .changed:
imgView.layer.transform = CATransform3DMakeTranslation(translation.x, translation.y, 0)
// OR
// imgView.transform = CGAffineTransform(translationX: translation.x, y: translation.y)
case .ended:
if deleteIcon.frame.intersects(imgView.layer.frame) {
animateDelete()
} else {
moveBack()
}
default:
moveBack()
}
}
func animateDelete() {
UIView.animate(withDuration: 0.3, animations: {
self.imgView.alpha = 0
}) { _ in
self.imgView.isHidden = true
}
}
func moveBack() {
UIView.animate(withDuration: 0.3) {
self.imgView.transform = CGAffineTransform.identity
}
}