Moveable

Discussion in 'iOS Programming' started by oxcug, Apr 23, 2012.

  1. oxcug macrumors newbie

    Joined:
    Oct 3, 2011
    #1
    I'm trying to figure out how to allow the user to move objects around the screen with their finger. I've seen some tutorials that do this with success but they don't work with multiple objects on the screen.
     
  2. jnoxx macrumors 65816

    jnoxx

    Joined:
    Dec 29, 2010
    Location:
    Aartselaar // Antwerp // Belgium
    #2
    Subclass an UIView of your own, implement the drag code, and send a delegate to your main window where you add them. i did this for some kid games, works like a charm.
     
  3. oxcug thread starter macrumors newbie

    Joined:
    Oct 3, 2011
    #3
    Can you show me the code for the dragging?
     
  4. jnoxx macrumors 65816

    jnoxx

    Joined:
    Dec 29, 2010
    Location:
    Aartselaar // Antwerp // Belgium
    #4
    It's all arond the internet, but i'm in a good mood so here.

    Code:
    - (void) setup {
        imageView = [[UIImageView alloc] initWithFrame:self.bounds];
        imageView.image = [UIImage imageNamed:self.imageName];
        [self addSubview:imageView];
        UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureMoveAround:)];
        [panRecognizer setMinimumNumberOfTouches:1];
        panRecognizer.delegate = self;
        [self addGestureRecognizer:panRecognizer];
        [panRecognizer release];
    }
    
    -(void)panGestureMoveAround:(UIPanGestureRecognizer *)gesture;
    {
        UIView *piece = [gesture view];
        [self bringSubviewToFront:piece];
        CGPoint translation = [gesture translationInView:[piece superview]];
        if ([gesture state] == UIGestureRecognizerStateChanged) {
            [piece setCenter:CGPointMake([piece center].x + translation.x, [piece center].y+translation.y)];
            [gesture setTranslation:CGPointZero inView:[piece superview]];
        } else if ([gesture state] == UIGestureRecognizerStateEnded) {
            [_delegate subclassView:self panningDidEnd:CGPointMake(self.frame.origin.x, self.frame.origin.y)];
        }
    }
    
    This is also included the custom delegate messages to the main view, this is inside the subclassed UIView.
     

Share This Page