2012-10-05 74 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) 
}