2012-10-05 44 views
3

我想知道UIScrollView中当前滚动页面的索引。我已经通过许多网站搜索没有帮助。 欢迎任何建议。ios:如何获取当前的索引?UIscrollView页面

+0

类似的问题是工作我[水平例子链接] http://stackoverflow.com/questions/4132993/getting-the-current-page – sash

+0

注意,这里的答案可能和使用views.index#!一样简单! ** let index = v.superview?.subviews.index(of:v)**在UIScrollView中完美工作 – Fattie

+0

[获取当前页面]的可能重复(http://stackoverflow.com/questions/4132993/getting-当前页面) – Can

回答

0

使用contentOffset属性,该属性返回UIScrollView中内容的偏移量CGSize

+0

将它除以scrollView的“bounds.size”,您将拥有“页码”。 – Cyrille

0

借助一些数学运算可以得到页面的索引号 我只发送代码供参考。我已经做好了。

-(void)KinarafindingSelectedCategory:(UIScrollView*)scrollView{ 
    for (UIView *v in scrollView.subviews) 
    { 
     if ([v isKindOfClass:[UIButton class]]) 
     { 
      UIButton *btn=(UIButton*)v; 

      float x1=scrollView.contentOffset.x+(([UIScreen mainScreen].bounds.size.width/2)-(btn.frame.size.width/2)); 
      float x2=scrollView.contentOffset.x+(([UIScreen mainScreen].bounds.size.width/2)+(btn.frame.size.width/2)); 
      float BtnMidPoint=btn.frame.origin.x+(btn.frame.size.width/2); 
      if(BtnMidPoint >= x1 && BtnMidPoint <= x2) 
      { 
       if(scrollView==KinaraCategory) 
       { 
        KinaraSelectedCategoryName=btn.titleLabel.text; 
        KinaraSelectedCategoryID=btn.tag; 
        NSLog(@"Selected Category Tag : %d",KinaraSelectedCategoryID); 
        NSLog(@"Selected Category Name : %@",KinaraSelectedCategoryName); 
       } 
       else if(scrollView==KinaraSubCategory) 
       { 
        KinaraSelectedSubCategoryID=btn.tag; 
        KinaraSelectedSubCategoryName=btn.titleLabel.text; 

        NSLog(@"Selected SubCategory Tag : %d",KinaraSelectedSubCategoryID); 
        NSLog(@"Selected SubCategory Name : %@",KinaraSelectedSubCategoryName); 
       } 
       break; 
      } 
     } 
    } 

} 
7

尝试此

//Horizontal 
    NSInteger pagenumber = scrollView.contentOffset.x/scrollView.bounds.size.width; 
    //Vertical 
    NSInteger pagenumber = scrollView.contentOffset.y/scrollView.bounds.size.height; 
+0

不是严格的相反吗? – Ben

+0

是的,我认为评论是相反的,将会改变它 –

3

对于那些需要代码(SWIFT),所述UIScrollViewDelegate提供的方法中,这使用来自上述

func scrollViewDidEndDecelerating(scrollView: UIScrollView) { 
    print("END Scrolling \(scrollView.contentOffset.x/scrollView.bounds.size.width)") 
    index = Int(scrollView.contentOffset.x/scrollView.bounds.size.width) 
}