Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 | -> |   |
|___|    |___|

This is what I have so far.

@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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
476 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...