Search code examples
iosuiviewuiscrollviewuiscrollviewdelegate

passing the data from uiscrollview with pagecontroller to another viewcontroller


I have a scrollview of images, I will like to tab them and will pushed to another view.

once i tab on the image, the whole view should push to another view. this my ScrollView.h as the following

@interface PeekPagedScrollViewController : UIViewController <UIScrollViewDelegate>

@property (nonatomic, strong) IBOutlet UIScrollView *scrollView;
@property (nonatomic, strong) IBOutlet UIPageControl *pageControl;

@end

and this is my images array as follow

- (void)viewDidLoad {
    [super viewDidLoad];

    // Set up the image you want to scroll & zoom and add it to the scroll view
    self.pageImages = [NSArray arrayWithObjects:
                       [UIImage imageNamed:@"photo1.png"],
                       [UIImage imageNamed:@"photo2.png"],
                       [UIImage imageNamed:@"photo3.png"],
                       [UIImage imageNamed:@"photo4.png"],
                       [UIImage imageNamed:@"photo5.png"],
                       nil];

so what i need when user touch the photo go to another detailViewController; for example if selected Photo1 this photo enlarge on another viewcontroller so if anybody knows the solution or suitable tutorial


Solution

  • Add a UITapGestureRecognizer to the UIScrollView, set the delegate yourself and then this method should give you the index of the tapped image:

    - (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture{
    
        CGPoint touchPoint = [gesture locationInView:<yourScrollView>];
    
        NSUInteger touchedPage = floorf(touchPoint.x / <yourScrollView>.frame.size.width);
        if ([<arrayOfImages> count>] > 1) {
    
            touchedPage = touchedPage % ([<arrayOfImages> count] - 1);
        }
    
        NSLog(@"Touched page: %d", touchedPage);
    
        //Use touchedPage and push the next view controller here
    
    }
    

    To add the gesture recognizer, add these lines into viewDidLoad (or you can use the IB):

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
    [<yourScrollView> addGestureRecognizer:singleTap];