Add UIScrollView with Paging to Existing UIViewController

后端 未结 3 1715
后悔当初
后悔当初 2021-01-13 08:27

I\'m wanting to add a UIScrollView with paging to go through different views from my existing view controller which is the root view of my app. I also have tab bar and navi

3条回答
  •  隐瞒了意图╮
    2021-01-13 08:58

    This works really well for me:

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

    @interface ViewController : UIViewController
    
    @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

    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;
    }
    

提交回复
热议问题