Add UIScrollView with Paging to Existing UIViewController

随声附和 提交于 2019-12-01 05:50:30

This works really well for me:

Declare a property for your UIScrollView, and set your ViewController as a UIScrollViewDelegate

@interface ViewController : UIViewController<UIScrollViewDelegate>

@property (strong, nonatomic) UIScrollView *theScrollView;

@end

**Note that I'm setting up my UIScrollView with code, but it can easily be done with a XIB.

In viewDidLoad: of your ViewController

    self.theScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, 300)];
    self.theScrollView.delegate = self;
    self.theScrollView.pagingEnabled = YES;
    self.theScrollView.showsHorizontalScrollIndicator = NO;     
    self.theScrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.theScrollView];

    NSArray *viewArray = [NSArray arrayWithObjects://your UIViews];

    for(int i=0; i<viewArray.count; i++)
    {
        CGRect frame;
        frame.origin.x = self.theScrollView.frame.size.width * i;
        frame.origin.y = 0;
        frame.size = self.theScrollView.frame.size;

        UIView *subview = [[UIView alloc] initWithFrame:frame];
        [subview addSubview:[viewArray objectAtIndex:i]];
        [self.theScrollView addSubview:subview];
    }

    self.theScrollView.contentSize = CGSizeMake(self.theScrollView.frame.size.width * viewArray.count, self.theScrollView.frame.size.height);

Most paging scrollViews also have a UIPageControl associated with it. To do that, override this UIScrollViewDelegate method:

- (void)scrollViewDidScroll:(UIScrollView *)sender {
    CGFloat pageWidth = self.theScrollView.frame.size.width;
    int page = floor((self.theScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    self.thePageControl.currentPage = page;
}

I would perhaps try using UIPageViewController, rather than a regular paging scrollview.

Apple's PhotoScroller sample code provides a very good example of how to use UIPageViewController.

I also have some code on github that modifies PhotoScroller to load the UIPageViewController inside a UIViewController subclass. (In Apple's sample code, the UIPageViewController is the root view controller.)

I have never used a UIPageViewController with different UIViewController subclasses in each page (the PhotoScroller sample code uses PhotoViewControllers in all pages), but I can't see why it couldn't be done with a few modifications to the code.

Maulik Kundaliya

This link helps for you. Here page controller and scrollview both are used -

PageControl Example in iPhone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!