我有一个包含n个占位符UIImageView的UIScrollView。下面我有一个包含10个图像的StackView,用户可以从中选择并将图像拖到上面的特定占位符图像视图中。我已经实现了PanGesture并且工作正常,但是,我正在努力解决如何检测可拖动图像何时在占位符图像的范围内。特别是因为它处于滚动视图中。我能够得到一些与center.X和center.Y一起工作的可拖动视图,然后检查这些值与占位符的相对值,但它没有按预期工作。从我所看到的,拖动的X和Y坐标,仅适用于实际的父UIView。因此,当图像被拖动到滚动视图中时,X值不一定排成一行,如果列表很长,那些占位符图像X坐标中的一些可能是2000+。看看下面的代码,让我知道您的想法和建议。谢谢!
@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
let translation = recognizer.translationInView(self.view)
if recognizer.state == UIGestureRecognizerState.Began {
originalViewLocation = recognizer.view!.center
}else if recognizer.state == UIGestureRecognizerState.Ended {
for placeHolderView in playerImages{
if ((recognizer.view!.center.x < (placeHolderView.center.x + (placeHolderView.frame.width / 2)) && recognizer.view!.center.x > placeHolderView.frame.origin.x)){
if recognizer.view!.center.y < (stackView.center.y + stackView.frame.height / 2){
let chosenImage = recognizer.view! as! UIImageView
placeHolderView.image = chosenImage.image
}
}else{
UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseInOut, animations: {
recognizer.view!.center = self.originalViewLocation
}, completion: { finished in
})
}
}
}
if let view = recognizer.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
}
recognizer.setTranslation(CGPointZero, inView: self.view)
print("X: \(recognizer.view!.center.x)")
print("Y: \(recognizer.view!.center.y)")
}
playerImages数组将UIImageViews存储在滚动视图中。
答案 0 :(得分:0)
我确实自己解决了这个问题。它与相对坐标值和实际坐标值有关。
我最终需要一些东西......
CGRectContainsPoint()
检查目标占位符视图的框架是否包含拖动视图的中心点。
和...
convertRect()
与
convertPoint()
我必须将拖动点的坐标值转换为superview的值。同时,将滚动视图中占位符视图的帧值转换为相同(超视图值)。像这样......
let convertedCenter = recognizer.view!.superview!.convertPoint(recognizer.view!.center, toView: self.view)
let convertedFrame = self.view.convertRect(IV.frame,fromView: IV.superview)
if CGRectContainsPoint(convertedFrame, convertedCenter) {
//Replace placeholder image with dragged image.
}
希望这会帮助别人。