UIPageControl + UIScrollView无法正确计算页面

时间:2014-09-03 01:48:22

标签: objective-c uiscrollview uipagecontrol

我遇到的问题是UIPageControl增加currentPage超过数组计数 - 1.例如;如果数组中有5个项目,它实际上会绘制5个点,但它只会到4个数字。控件会根据UIScrollView的分页增加或减少(我认为会是)给定数组中的最大项数。任何帮助,将不胜感激。

这是scrollViewDidEndDecelerating的代码:

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
CGFloat pageWidth = _meatSelectionCollection.frame.size.width;
self.pageControl.currentPage = _meatSelectionCollection.contentOffset.x / pageWidth;
NSLog(@"Current Page Test: %ld", (long)self.pageControl.currentPage);
}

我在UIScrollView中检测确定当前页面的页面宽度,并启用滚动视图中的分页。但是,当页面的NSLog会在页面更改时读取以下输出:

2014-09-02 21:41:28.359 Burger Grinder[73531:60b] Current Page Test: 0
2014-09-02 21:41:29.420 Burger Grinder[73531:60b] Current Page Test: 1
2014-09-02 21:41:30.120 Burger Grinder[73531:60b] Current Page Test: 2
2014-09-02 21:41:30.870 Burger Grinder[73531:60b] Current Page Test: 3
2014-09-02 21:41:31.708 Burger Grinder[73531:60b] Current Page Test: 4
2014-09-02 21:41:32.476 Burger Grinder[73531:60b] Current Page Test: 4

它没有递增超过4.确定它的数组计数返回为6.我知道显示self.page.currentPage的{​​{1}}是计算4的结果(即5个元素),但计数为6。

有关可能导致此问题的任何想法?提前谢谢。

编辑:增加后显示内容偏移和页面宽度日志:

0, 1, 2, 3, 4

事实上,即使计数没有超过4,2014-09-02 22:03:52.472 Burger Grinder[73813:60b] Current Page Test: 1 2014-09-02 22:03:52.472 Burger Grinder[73813:60b] Content Offset.x Value: 244.000000 2014-09-02 22:03:52.473 Burger Grinder[73813:60b] PageWidth: 244.000000 2014-09-02 22:03:55.811 Burger Grinder[73813:60b] Current Page Test: 2 2014-09-02 22:03:55.811 Burger Grinder[73813:60b] Content Offset.x Value: 488.000000 2014-09-02 22:03:55.812 Burger Grinder[73813:60b] PageWidth: 244.000000 也会递增。它会在最高级别页面上将值正确记录为Content Offset.x Value,但计数器不会增加。

1 个答案:

答案 0 :(得分:0)

原来这是计算currentPage的一个问题。重新下面:

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
CGFloat pageWidth = _meatSelectionCollection.frame.size.width;
//    self.pageControl.currentPage = _meatSelectionCollection.contentOffset.x / pageWidth;

// This is where it needed to be calculated correctly rather then the line above it.

int page = floor((_meatSelectionCollection.contentOffset.x - pageWidth / 2) / pageWidth) + 1; 

self.pageControl.currentPage = page;


NSLog(@"Current Page Test: %ld", (long)self.pageControl.currentPage);
NSLog(@"Content Offset.x Value: %f", _meatSelectionCollection.contentOffset.x);
NSLog(@"PageWidth: %f", pageWidth);
NSLog(@"Scroll View: %f", scrollView.contentSize.width);
}