Question

I'm trying to implement page control and scroll view using an image array, and for some reason, my images are shifting around when swiping to the next page. It almost seems like the images are too big for the scroll view, but making them smaller doesn't seem to work. Is there a way to make it so that the ScrollView doesn't "scroll" vertically? See code below.

enter image description here

SSViewController.h

#import <UIKit/UIKit.h>

@interface SSViewController : UIViewController <UIScrollViewDelegate>

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


@property (nonatomic, strong) NSArray *imageArray;

SSViewController.m

 -(void)viewDidAppear:(BOOL)animated
{

   imageArray = [[NSArray alloc] initWithObjects:@"first.png", @"second.png", nil];

for (int i = 0; i < [imageArray count]; i++) {
    //We'll create an imageView object in every 'page' of our scrollView.
    CGRect frame;
    frame.origin.x = self.scrollView.frame.size.width * i;
    frame.origin.y = 0;
    frame.size = self.scrollView.frame.size;

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
    imageView.image = [UIImage imageNamed:[imageArray objectAtIndex:i]];
    size:imageView.clipsToBounds = YES;
    imageView.contentMode = UIViewContentModeScaleAspectFill;

    [self.scrollView addSubview:imageView];
}
//Set the content size of our scrollview according to the total width of our imageView objects.
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * [imageArray count], scrollView.frame.size.height);
}


    - (void)scrollViewDidScroll:(UIScrollView *)sender
    {
        // Update the page when more than 50% of the previous/next page is visible
        CGFloat pageWidth = self.scrollView.frame.size.width;
        int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
        self.pageControl.currentPage = page;
        self.scrollView.contentOffset = CGPointMake(self.scrollView.contentOffset.x, 0);

    }
Was it helpful?

Solution

I think good idea will be to shift all your allocaton code (espacially all code define frames) to viewWillAppear method, because in viewDidLoad some frame wouldn't be already set.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top