Search code examples
iosxcodeuiscrollviewscrollview

Handling touches within UIScrollview


I have a view that contains a UIScrollView. The UIScrollView contains an UIImageView (only one for now but there will be more latter). I want to be able to drag the UIImageView out of the UIScrollView and into the superview.

I have reviewed every similar question and example I can find online and still cant get my head around how this works.

At first I couldn't get touches to register all whithin the scrollview. After a lot of searching I have found a way to get touchesbegan to register as follows:

First I created a new view based project and in the auto-created "ViewController.h" I created an IBOutlet named slider.

Then in the auto-created "ViewController.m" I created the UIScrollview.

In IB I added a UIScrollView to the storyboard then connected it to the "slider" IBOutlet.

Next I added class file to the projects. This new class is a subclass os UIImageView. I named this class "DragableImage" In the

Then in IB I dropped an image into the UIScrollview clicked on it and changed the class to "DragableImage"

In the DragableImage.m I voided touches began and simply told it to become hidden if clicked.

This works and the touch registers and makes the image disappear but how do I now add the new image to the main view and have it follow my finger?

This is what I have in the way of code:

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController {

    IBOutlet UIScrollView *slider;
}

@end

ViewController.m

#import "ViewController.h"


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [slider setScrollEnabled:YES];
    [slider setContentSize:CGSizeMake(306, 1560)];
    [slider setShowsVerticalScrollIndicator:NO];
    slider.canCancelContentTouches = NO; 
    slider.delaysContentTouches = NO;

    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

@end

DragableImage.h

#import <UIKit/UIKit.h>

@interface DragableImage : UIImageView

@end

DragableImage.m

@implementation DragableImage

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    self.hidden = YES;
}

@end

How to make this work?


Solution

  • There is one obvious problem that can arise here. Namely, how to tell the difference between dragging to scroll and dragging an image. The way I would handle this is to setup a tap and hold gesture recognizer (http://developer.apple.com/library/ios/#documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/GestureRecognizers/GestureRecognizers.html).

    Once you detect a hold you could set it up so that further touches/gestures get routed to you drag and drop code. You can find a nice tutorial for that here: http://www.ancientprogramming.com/2012/04/05/drag-and-drop-between-multiple-uiviews-in-ios/