用按钮更改页面控制

时间:2012-04-07 22:40:09

标签: iphone objective-c ios

我有一个简单的页面控件设置有两个不同的页面。我有一个名为nextButton的按钮,如果用户点击该按钮,我想更改页面并滚动到下一页。

我的页面控件有效,我可以滚动到更改页面,但按钮根本不起作用。它正在被召唤。

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * TUTORIALNUMBEROFPAGES, self.scrollView.frame.size.height);
    self.scrollView.pagingEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.scrollsToTop = NO;
    self.scrollView.delegate = self;

    self.pageControl.numberOfPages = TUTORIALNUMBEROFPAGES;
    self.pageControl.currentPage = 0;

    CGRect pageFrame = self.scrollView.frame;
    pageFrame.origin.x = pageFrame.size.width * 0;
    pageFrame.origin.y = 0;

    self.pageOne.frame = pageFrame;
    [self.scrollView addSubview:self.pageOne];

    pageFrame.origin.x = pageFrame.size.width * 1;
    self.pageTwo.frame = pageFrame;
    [self.scrollView addSubview:self.pageTwo];
}

- (void)scrollViewDidScroll:(UIScrollView *)sender 
{    
    if (pageControlUsed) {
        return;
    }

    CGFloat pageWidth = self.scrollView.frame.size.width;
    int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    self.pageControl.currentPage = page;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView 
{    
    pageControlUsed = NO;
}

- (IBAction)changePage:(id)sender 
{        
    NSInteger currentPage = self.pageControl.currentPage;
    CGPoint offset = CGPointMake(currentPage * self.scrollView.frame.size.width, 0);
    [self.scrollView setContentOffset:offset animated:YES];
    pageControlUsed = YES;
}

- (IBAction)nextButton:(id)sender
{
    [self changePage:self];
}

2 个答案:

答案 0 :(得分:7)

尝试这样的事情:

 - (IBAction)nextPage:(id)sender 
  {        
     NSInteger currentPage = self.pageControl.currentPage + 1;
     CGPoint offset = CGPointMake(currentPage * self.scrollView.frame.size.width, 0);
    [self.scrollView setContentOffset:offset animated:YES];
    pageControlUsed = YES;
 }

  - (IBAction)nextButton:(id)sender
  {
      [self nextPage:self];

  }

注意该代码中的+1。在此之前,您实际上将内容偏移精确度设置为等于原始偏移量,因为您只是获取页面控件的值。

答案 1 :(得分:1)

你可以试试这个:

- (IBAction)changePage:(id)sender 
{        
    NSInteger currentPage = self.pageControl.currentPage;
    if([sender isKindOfClass:[UIButton class]){
       currentPage+=1;
    }
    CGPoint offset = CGPointMake(currentPage * self.scrollView.frame.size.width, 0);
    [self.scrollView setContentOffset:offset animated:YES];
    pageControlUsed = YES;
}

- (IBAction)nextButton:(id)sender
{
    [self changePage:sender];//if this action is attached just to your button
}