Using UIPageControl as a container UIViewController(二)
oller = [self.childViewControllers objectAtIndex:page];
if(controller == nil) {
return;
}
// add the controller's view to the scroll view
if(controller.view.superview == nil) {
CGRect frame = self.scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller.view.frame = frame;
[self.scrollView addSubview:controller.view];
}
}
处理滚动
为了处理滚动,我们需要实现几个 UIScrollViewDelegate 的方法以及尽早声明方法 - (IBAction)changePage:(id)sender
首先必须先知道滚动是如何实现的,要么是手势,要么就是点击了 UIPageControl 的一侧。
来一起看看下面的代码:
[cpp]
// At the begin of scroll dragging, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
_pageControlUsed = NO;
}
// At the end of scroll animation, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
_pageControlUsed = NO;
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
UIViewController *oldViewController = [self.childViewControllers objectAtIndex:_page];
UIViewController *newViewController = [self.childViewControllers objectAtIndex:self.pageControl.currentPage];
[oldViewController viewDidDisappear:YES];
[newViewController viewDidAppear:YES];
_page = self.pageControl.currentPage;
}
现在,为了当页面改变时也能更新当前的显示,我们只需要实现 scrollViewDidScroll delegate方法以及 changePage IBAction 方法。
[cpp]
- (IBAction)changePage:(id)sender {
intpage = ((UIPageControl *)sender).currentPage;
// update the scroll view to the appropriate page
CGRect frame = self.scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
UIViewController *oldViewController = [self.childViewControllers objectAtIndex:_page];
UIViewController *newViewController = [self.childViewControllers objectAtIndex:self.pageControl.currentPage];
[oldViewController viewWillDisappear:YES];
[newViewController viewWillAppear:YES];
[self.scrollView scrollRectToVisible:frame animated:YES];
// Set the boolean used when scrolls originate from the UIPageControl. See scrollViewDidScroll: above.
_pageControlUsed = YES;
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
// which a scroll event generated from the user hitting the page control triggers updates from
// the delegate method. We use a boolean to disable the delegate logic when the page control is used.
if(_pageControlUsed || _rotating) {
// do nothing - the scroll was initiated from the page control, not the user dragging
return;
}
// Switch the indicator when more than 50% of the previous/next page is visible
CGFloat pageWidth = self.scrollView.frame.size.width;
intpage = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
if(self.pageControl.currentPage != page) {
UIViewController *oldViewCo