使用pageControl和ScrollView ios滚动到特定页面

时间:2015-09-22 07:19:47

标签: ios objective-c uiscrollview uipagecontrol

我知道此问题已被提及,但我没有得到任何具体的答案。我正在使用页面控件和scrollView添加视图控制器,然后使用滑动显示所有页面。我需要在按钮点击时重定向到特定页面。我尝试了scrollView SetcontentOffet和其他所有可能性。

-(void)ScrollToPage:(int)page
{
 UIViewController *controller = [self.childViewControllers objectAtIndex:page];
 if (controller.view.superview == nil)
 {
      CGRect frame = self.scrollView.frame;
      if (frame.size.width == 0)
      {
           frame.size.width = self.view.frame.size.width;
           frame.size.height = self.view.frame.size.height;
      }
      frame.origin.x = frame.size.width * page;
      frame.origin.y = 0;
      controller.view.frame = frame;

      [scrollView setContentOffset:CGPointMake(frame.origin.x, frame.origin.y) animated:YES];
      self.pageControl.currentPage = page;
      [self centerScrollViewContents];
      [self.scrollView setContentOffset:CGPointMake(frame.origin.x, frame.origin.y)];
      [self.scrollView scrollRectToVisible:frame animated:YES];
      [self.scrollView addSubview:controller.view];
 }
}

1 个答案:

答案 0 :(得分:0)

我认为您的网页正在密切使用您的设备宽度。只需按照以下步骤操作即可。

- (void)viewWillAppear:(BOOL)animated {
      self.myCurrentPage = 0;
      [self setScrollViewPages];
      self.scrollView.delegate = self;
}

- (void)setScrollViewPages {
   for (int i = 0; i < numberOfPages; i++) {
       UIView *myPageView = [[UIView alloc]initWithFrame:(CGRect) {self.view.frame.size.width * i
        + 10.0f,10.0f,self.view.frame.size.width - 20.0f , self.scrollView.frame.size.height-20.0f}];
       myPageView.backgroundColor = [UIColor greenColor];

       [self.scrollView addSubview:myPageView];

    }

}

按钮单击

- (IBAction)buttonClicked:(id)sender {

//Pass the requried page, by default I'm passing 4
self.myCurrentPage = 4;
[self updateMyScrollView];
}

相应的滚动视图设置为

- (void)updateMyScrollView {
  [self.scrollView setContentOffset:CGPointMake(self.view.frame.size.width *self.myCurrentPage, 0) animated:YES];
  self.pageControl.currentPage = self.myCurrentPage;
}

此外,您的scrollview委托就像这样......

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
int pageWidth = self.view.frame.size.width ;
int pageX = self.myCurrentPage*pageWidth - scrollView.contentInset.left;
if (targetContentOffset->x<pageX) {
    if (self.myCurrentPage>0) {
        self.myCurrentPage--;
    }
}
else if(targetContentOffset->x>pageX){
    if (self.myCurrentPage < numerOfPages) {
        self.myCurrentPage++;
    }
}
targetContentOffset->x = self.myCurrentPage*pageWidth-scrollView.contentInset.left;
DLog(@"%ld %d", (long)self.myCurrentPage, (int)targetContentOffset->x);
self.pageControl.currentPage = self.myCurrentPage;
}

希望这会有所帮助......