IOS - Centering UIScrollView inside UIView contain

2019-08-28 02:49发布

问题:

I'm trying to replicate the safari pages scrollview, which has its frame that is slightly narrower than iPhone screen. So According to few suggestions I'm placing a the scrollview (450x280 points) inside a "clipView" (450x320 points).

//viewController methods
-(void)viewDidAppear:(BOOL)animated{

CGRect pagingScrollViewFrame = self.clipview.frame;
pagingScrollViewFrame.size.width = 280;

NSLog(@"clipview h:%f e w:%f",self.clipview.frame.size.height,self.clipview.frame.size.width);
NSLog(@"scrollview h:%f e w:%f",pagingScrollViewFrame.size.height,pagingScrollViewFrame.size.width);
NSLog(@"center clipview :%@",NSStringFromCGPoint(self.clipview.center));

pagingScrollView = [[UIScrollView alloc] initWithFrame:pagingScrollViewFrame];
NSLog(@"center scrollview:%@",NSStringFromCGPoint(pagingScrollView.center));
pagingScrollView.contentSize = CGSizeMake(pagingScrollViewFrame.size.width *3, pagingScrollViewFrame.size.height);

pagingScrollView.clipsToBounds = NO;
pagingScrollView.center = self.clipview.center;

    [clipview addSubview:pagingScrollView];
}

As you can see I have my scrollView's center That is shifted 20points down ({140, 232}). My view Container has its center at {160, 232}.

Where am I wrong?There is anything like content offset property I should play with? is this issue related to Autolayout ?

回答1:

The issue is in this line:

pagingScrollView.center = self.clipview.center;

Should be:

pagingScrollView.center = CGPointMake(CGRectGetMidX(self.clipview.bounds), CGRectGetMidY(self.clipview.bounds));

It is common mistake to assign center of superview to its subview. They are in different coordinate systems.