Pablo Garcia
Pablo Garcia

Reputation: 381

Center content into UIScrollView (Pager) iOS

i have a two UIScrollviews with pager enabled and i add 12 UIImageViews dynamically.

enter image description here

I have the next code:

int content_size_width = self.view.frame.size.width - arrow_left.frame.size.width - arrow_right.frame.size.width;
int content_size_height = green_scroll.frame.size.height;
first_sign_scroll.frame = CGRectMake(0, 0, content_size_width, content_size_height);
first_sign_scroll.pagingEnabled=YES;
first_sign_scroll.contentSize = CGSizeMake(content_size_width*12,1);
int pos = 0;
for(int i=1;i<13;i++){

    UIImage *img = [UIImage imageNamed:images_array[i-1]];
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, img.size.width*multiple, img.size.height*multiple)];
    [image setImage: img];

    float middle_scroll_x = green_scroll.frame.size.width/2;
    float middle_scroll_y = green_scroll.frame.size.height/2;

    image.center = CGPointMake(middle_scroll_x + pos,middle_scroll_y);
    [green_scroll addSubview:image];
    pos +=content_size_width;

}

I did the same code for the blue scroll.

The problem is the images aren't in the center of the scrollview as you can see in the image. The vertically center doesn't work.

Could someone help me?

Thanks.

Upvotes: 0

Views: 196

Answers (1)

Pasha_Molodkin
Pasha_Molodkin

Reputation: 51

Try this method to center :

@implementation ContentInsetCenteredScrollView

    - (void)centerContent {
        CGFloat top = 0, left = 0;
        if (self.contentSize.width < self.bounds.size.width) {
            left = (self.bounds.size.width-self.contentSize.width) * 0.5f;
        }
        if (self.contentSize.height < self.bounds.size.height) {
            top = (self.bounds.size.height-self.contentSize.height) * 0.5f;
        }
        self.contentInset = UIEdgeInsetsMake(top, left, top, left);
    }

    - (void)didAddSubview:(UIView *)subview {
        [super didAddSubview:subview];
        [self centerContent];
    }

    - (void)scrollViewDidZoom:(__unused UIScrollView *)scrollView {
        [self centerContent];
    }

    - (void)setFrame:(CGRect)frame {
        [super setFrame:frame];
        [self centerContent];
    }

Upvotes: 2

Related Questions