Tom
Tom

Reputation: 3627

Scrolling and zooming UIImageView in an UIScrollView

When I try to scroll or zoom, nothing happens.

...

I have a scrollview I setup in viewDidLoad() like this

outletCatalogDetailsScrollViewImage.delegate = self;
outletCatalogDetailsScrollViewImage.minimumZoomScale = 1.0;
outletCatalogDetailsScrollViewImage.maximumZoomScale = 10.0;

...

func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
  var res: UIView? = nil;
  if scrollView == outletCatalogDetailsScrollViewImage {
    res = self.outletCatalogDetailsImage;
  }
  return res;
}

In this scrollview I have the imageview.

To avoid warnings in XCode designer I have the following constraints defined in my UIScrollView:

Outlet Catalog Details Image.Center Y = Superview.Center Y
Outlet Catalog Details Image.Center X = Superview.Center X
bottom = Outlet Catalog Details Image.bottom
trailing = Outlet Catalog Details Image.trailing
Outlet Catalog Details Image.top = top
Outlet Catalog Details Image.leading = leading

And in main view:

Outlet Catalog Details Scroll View Image.leading = Navigation Bar.leading
trailingMargin = Outlet Catalog Details Scroll View Image.trailing

...

I also have a "equal height" height constraint between the scrollview and another view below.

I suspect my constraints are the reason zoom/pan is not working. I am hoping I am missing a better way to configure constraints

Upvotes: 0

Views: 762

Answers (1)

tktsubota
tktsubota

Reputation: 9391

Your suspicion is correct. The constraints are the problem.

You mentioned that you had to avoid warnings in the storyboard, so you put those constraints. However, those constraints are the problematic ones. Mainly, these 4:

bottom = Outlet Catalog Details Image.bottom
trailing = Outlet Catalog Details Image.trailing
Outlet Catalog Details Image.top = top
Outlet Catalog Details Image.leading = leading

The image has its own width and height, so why should it have to be constrained to the scroll view's width and height? The idea of a scroll view is that it moves all its subviews around by changing its bounds. The scroll view isn't actually bigger than the screen, it's subviews are.

How can you fix this? You want to have no storyboard warnings, but you don't want these constraints. You can do one of two things:

  1. Create the image view in code
  2. Add placeholder constraints in the storyboard

For your case, I highly recommend placeholder constraints. In your storyboard, click on your image view. Then, go to the Size Inspector, which is the fifth tab from the left on the right navigator.

Size Inspector

Then, scroll down to where it says "Constraints". Double-click on one of the problematic constraints (see above), and find the "Remove at build time" checkbox.

enter image description here

Enable that checkbox, and then repeat that for the other three constraints.

Upvotes: 1

Related Questions