Is it possible to have a UIImageView inside of a UIScrollView zoom in and out, but stick to center with Auto Layout?

后端 未结 2 1194
孤街浪徒
孤街浪徒 2021-02-15 13:14

Long story short, I\'m trying to build functionality similar to Photos.app.

I have a UIScrollView with a UIImageView inside of it set up in the Storyboard. Zooming works

2条回答
  •  有刺的猬
    2021-02-15 13:22

    To center the contents, you can take reference from this code snippet:

    // To re-center the image after zooming in and zooming out
    - (void)centerScrollViewContents
    {
     CGSize boundsSize = self.bounds.size;
     CGRect contentsFrame = self.imageView.frame;
    
     if (contentsFrame.size.width < boundsSize.width)
     {
       contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
     }
     else
     {
      contentsFrame.origin.x = 0.0f;
     }
    
     if (contentsFrame.size.height < boundsSize.height)
     {
      contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
     }
     else
     {
        contentsFrame.origin.y = 0.0f;
     }
    
     self.imageView.frame = contentsFrame;
    }
    
    //for zooming in and zooming out
    - (void)scrollViewDidZoom:(UIScrollView *)scrollView
     {
      if (self.zoomScale > 1.0f)
      {
        [self centerScrollViewContents];
      }
       else
      {
      self.bouncesZoom    =   NO;
    
        // for zooming out by pinching
      [self centerScrollViewContents];
      }
    
     }
    

    In this way, you can reposition the coordinates of an image after zooming in and zooming out without AutoLayout. Please let me know if it helps. Thanks :)

提交回复
热议问题