Martin Perry
Martin Perry

Reputation: 9527

UIScrollView and UIImageView - move horizontally

I have UIScrollView with UIImageView on it. I set image in code and it can have different width (height is always the same). I want to do it scrollable (eg. see only part of it and drag it to left / right to see the rest).

I have this code performed after image change:

float x = self.imageView.frame.origin.x;
float y = self.imageView.frame.origin.y;
float w = scaleImg.size.width;
float h = scaleImg.size.height;

self.imageView.frame = CGRectMake(x, y, w, h);
self.imageView.bounds = CGRectMake(0, 0, w, h);


w = self.frame.size.width;
h = self.scrollView.frame.size.height;

[self.scrollView setContentSize: CGSizeMake(w + 20, h)];

Problem is, that it didn't scroll correctly (I think it didn't scroll at all). And after I scroll, my image is resized, not respecting the frame I have set above.

I am using iOS7, storyboard, autolayout.

Upvotes: 0

Views: 875

Answers (3)

Matic Oblak
Matic Oblak

Reputation: 16774

If you want the image to fit the scrollview and be scrollable left and right only you should create the image view with height same as the scrollview and width scaled accordingly to the image. Try something like this:

    UIImage *image;
    UIScrollView *scrollView;
    UIImageView *imageView;

    imageView = [[UIImageView alloc] initWithFrame:CGRectMake(.0f,
                                                              .0f,
                                                              scrollView.frame.size.height*image.size.width/image.size.height,
                                                              scrollView.frame.size.height)];//fixed height
    imageView.image = image;
    imageView.contentMode = UIViewContentModeScaleToFill;
    [scrollView addSubview:imageView];
    scrollView.contentSize = imageView.frame.size;
    scrollView.contentOffset = CGPointMake((scrollView.contentSize.width-scrollView.frame.size.width)*.5f, .0f);//scroll to center

Note I designed this only for images which have proportionally larger width then scrollview. If that is not always the case you should create a specific logic for other images (either background is visible or it is scrollable in Y coordinate).

Upvotes: 1

madhu
madhu

Reputation: 981

you given the w as the width for both scrollview and imageview....content size should be more than scroll view.Try giving imageview width more than scrollview.

Upvotes: 0

Nikolay Mamaev
Nikolay Mamaev

Reputation: 1474

I guess you should remove the following lines:

w = self.frame.size.width;
h = self.scrollView.frame.size.height;

scrollView's content size should reflect size of enclosed content, i.e. it should be scaleImg.size.width & scaleImg.size.height.

Upvotes: 0

Related Questions