简体   繁体   English

ios:如何获取当前的索引?UIscrollView页面

[英]ios: how to get index of current ?UIscrollView page

I want to know index of current scrolled page in UIScrollView. 我想知道UIScrollView中当前滚动页面的索引。 I have searched through many sites by none helps. 我搜索了许多网站没有帮助。 Any suggestions are welcome. 欢迎任何建议。

Try this 尝试这个

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

For those needing code (swift) , the UIScrollViewDelegate provides the method, this uses the horizontal example from above 对于那些需要代码(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)
}

使用contentOffset属性,该属性返回一个CGSize ,它是UIScrollView内容的偏移量。

with the help of some mathematical calculation you can get index number of page I am sending code for reference only . 在一些数学计算的帮助下,您可以获得我发送代码的页面的索引号,仅供参考。 I have done. 我已经做好了。

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM