我有一个程序,其中一个集合出口循环,以便为每个图像提供一个CGpoint来确定其原点位置并对每个图像应用平移手势。
然而,我的问题是当平移手势结束时,图片应该快速回到其开始时确定的原点位置。但是当我这样做时,
if sender.state == UIGestureRecognizerState.Ended {
for image in imageCollection {
image.center = positionOrigin
}
图像移回到与其他图像不同的位置/相同的位置。 我想这是因为我没有通过索引将CGPoint原点与每个图像相关联(例如,使用字典是有意义的吗?)。 任何人都知道如何解决这个问题?
这是我的代码:
import UIKit
class ViewController: UIViewController, UIGestureRecognizerDelegate {
@IBOutlet var imageCollection: [UIImageView]!
var positionOrigin: CGPoint!
override func viewDidLoad() {
super.viewDidLoad()
for image in imageCollection {
positionOrigin = image.center
let recognizer = UIPanGestureRecognizer(target: self, action: #selector(ViewController.handlePan))
recognizer.delegate = self
image.addGestureRecognizer(recognizer)
}
}
func handlePan(sender:UIPanGestureRecognizer) {
let translation = sender.translationInView(self.view)
if let view = sender.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
sender.setTranslation(CGPointZero, inView: self.view)
}
if sender.state == UIGestureRecognizerState.Ended {
for image in imageCollection {
image.center = positionOrigin
}
}
}
}
答案 0 :(得分:0)
这部分是问题var positionOrigin: CGPoint!
它在循环中的值发生了变化,所以最后它只有最后一个图像位置,
您可以使用具有 positionOrigin 属性的图像的子类,或使用positionOrigin数组来保存每个图像的原点位置。
答案 1 :(得分:0)
在@Dasem的帮助下,我能够得出以下问题的答案:
ViewController.swift
import UIKit
class ViewController: UIViewController, UIGestureRecognizerDelegate {
@IBOutlet var imageCollection: [UIImageView]!
var originPositions=[CGPoint]()
override func viewDidLoad() {
super.viewDidLoad()
for image in imageCollection {
originPositions.append(image.center)
print(originPositions)
let recognizer = UIPanGestureRecognizer(target: self, action: #selector(ViewController.handlePan))
recognizer.delegate = self
image.addGestureRecognizer(recognizer)
}
}
func handlePan(sender:UIPanGestureRecognizer) {
let translation = sender.translationInView(self.view)
if let view = sender.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
sender.setTranslation(CGPointZero, inView: self.view)
}
if sender.state == UIGestureRecognizerState.Ended {
for i in 0 ..< imageCollection.count {
imageCollection[i].center = originPositions[i]
}
}
}
}