在 UIView 之间拖动 UIView [英] Drag UIView between UIViews
问题描述
我有一个 UIView 对象 X,它包含在 UIView 对象 A 中.我希望能够触摸 X 并将其从对象 A 中移除并将其移动到对象 B(另一个 UIView)中.对象 A 和B 在同一个超级 UIView 内.
I have a UIView object X that is contained in an UIView object A. I want to be able to touch X and remove it from object A and move it into object B (another UIView). Both Object A & B are inside of the same super UIView.
A B
_____ _____
| | | |
| X | -> | |
|___| |___|
这是我目前所拥有的.
@implementation X_UIView
float deltaX;
float deltaY;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.superview.superview addSubview:self]; //pop dragged view outside of container view
CGPoint beginCenter = self.center;
UITouch * touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:self.superview];
deltaX = touchPoint.x - beginCenter.x;
deltaY = touchPoint.y - beginCenter.y;
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
UITouch * touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:self.superview];
// Set the correct center when touched
touchPoint.x -= deltaX;
touchPoint.y -= deltaY;
self.center = touchPoint;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
//discover view that event ended was over and add self as a subview.
}
@end
推荐答案
调用[[touches anyObject] locationInView: self.superview]
获取容器视图中手指下的点.然后发送 self.superview -hitTest:withEvent:
找出视图 X 在里面.请注意,它将始终返回 X,因此您必须在拖动时覆盖 -pointIsInside:withEvent:
或 -hitTest:withEvent:
以返回 nil.这种混乱是我在容器视图中实现这种跟踪的原因,而不是在拖动视图中.
Call [[touches anyObject] locationInView: self.superview]
to get the point under the finger in the container view. Then send self.superview -hitTest:withEvent:
to find out the view X is inside. Note that it will always return X, so you will have to override either -pointIsInside:withEvent:
or -hitTest:withEvent:
to return nil while you're dragging. This kind of kludge is the reason I would implement such tracking in the container view, rather than in a dragged view.
这篇关于在 UIView 之间拖动 UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!