Search code examples
iosobjective-cuiscrollview

How to keep UIView center using UIScrollview contentoffset iOS?


I have UIView inside of UIScrollView which contains 4 subviews. while tapping on subview i want to adjust scrollview's contentoffset property in such way that my tapped subview is align to center of screen.

I tried some logic but it not working properly.

-(void)onDragViewTapped:(UITapGestureRecognizer *)recognizer
{
    CGFloat width = self.scrollVw.contentSize.width/2;
    CGFloat vwWidth = recognizer.view.frame.size.width/2;
    width = width - vwWidth - vwWidth/self.scrollVw.zoomScale - 
    width/self.scrollVw.zoomScale;

    CGFloat height = self.scrollVw.contentSize.height/2;
    CGFloat vwHeigh = recognizer.view.frame.size.height/2;
    height = height- vwHeigh -  vwHeigh/self.scrollVw.zoomScale - 
    height/self.scrollVw.zoomScale;

    [self.scrollVw setContentOffset:CGPointMake(width, height) 
    animated:YES];
}

Solution

  • This works for me (without zooming actually):

    // This view below here is the view of the view controller, 
    // use the container view instead to align the center to
    let newX = tappedView.center.x - view.center.x
    let newY = tappedView.center.y - view.center.y
    scrollview.setContentOffset(CGPoint(x: newX, y: newY), animated: true)