Getting the current page

2019-01-29 19:19发布

In my scroll view, I want to get the current page that's being displayed (maybe page isn't the correct term). I can't find any variable that holds this. But I think it must be held somewhere, since the indicator is able to show which sub-view of the scroll view is currently being displayed.

Is this hidden from us completely or is there a way for me to access it?

13条回答
虎瘦雄心在
2楼-- · 2019-01-29 19:21

Just divide the current offset by the page size:

CGFloat pageNum = (int)(scrollView.contentOffset.x / scrollView.frame.size.width);
查看更多
霸刀☆藐视天下
3楼-- · 2019-01-29 19:24

Are you using a UIPageControl? If so, this has a currentPage property. If not, I think you'll need to calculate the page index from the scrollView offset.

查看更多
你好瞎i
4楼-- · 2019-01-29 19:28

Another way:

extension MyViewController: UIScrollViewDelegate {
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let width = scrollView.frame.width
        let page = Int(round(scrollView.contentOffset.x/width))
        print("CurrentPage:\(page)")
    }
}
查看更多
Luminary・发光体
5楼-- · 2019-01-29 19:31

In xCode 7.x swift 2.x you can do :

//MARK: - ScrollView Extensions
// Get the current page number
extension UIScrollView {
    var currentPage: Int {
        return Int(round(self.contentOffset.x / self.bounds.size.width))
    }

// If you have reversed offset (start from contentSize.width to 0)
    var reverseCurrentPage: Int {
        return Int(round((contentSize.width - self.contentOffset.x) / self.bounds.size.width))-1
    }
}
查看更多
霸刀☆藐视天下
6楼-- · 2019-01-29 19:40

In swift I would do it in extension:

extension UIScrollView {
    var currentPage:Int{
        return Int((self.contentOffset.x+(0.5*self.frame.size.width))/self.frame.width)+1
    }
}

Then just call:

scrollView.currentPage
查看更多
孤傲高冷的网名
7楼-- · 2019-01-29 19:41

If Any one Looking for way of doing in C# for Xamarin

    public int CurrentIndex
    {
        get => (int)Math.Round(this.scrollView.ContentOffset.X / this.scrollView.Frame.Width);
        set => this.scrollView.ScrollRectToVisible(new CGRect(new CGPoint(this.scrollView.Frame.Size.Width * value, 0), this.scrollView.Frame.Size), true);
    }

This getter and Setter should provide you current page as well let you scroll to the specified page

查看更多
登录 后发表回答