Page count of UICollectionView with paging in iOS

hpi*_*que 9 iphone uipagecontrol ios ios6 uicollectionview

Consider a UICollectionView with flow layout and paging enabled (by setting pagingEnabled to YES).

What would be the simplest way of obtaining the total number of pages?

And where would be the most appropriate place to update the total number of pages (given that it might change if items are added/deleted, the size of the collection view changes or the layout changes)?

nah*_*g89 7

正确的答案应该是:

如果UICollectionView水平滚动:

int pages = ceil(self.collectionView.contentSize.width /    
                   self.collectionView.frame.size.width);
Run Code Online (Sandbox Code Playgroud)

如果它垂直滚动:

 int pages = ceil(self.collectionView.contentSize.height /    
                   self.collectionView.frame.size.height);
Run Code Online (Sandbox Code Playgroud)

关注维基:

在数学和计算机科学中,floor和ceiling函数分别将实数映射到最大的前一个或最小的下一个整数.更确切地说,floor(x)是不大于x的最大整数,而ceiling(x)是不小于x的最小整数.

这是我要检查的结果:

ceil(2.0/5.0) = 1.000000
ceil(5.0/5.0) = 1.000000
ceil(6.0/5.0) = 2.000000
ceil(10.0/5.0) = 2.000000
ceil(11.0/5.0) = 3.000000
Run Code Online (Sandbox Code Playgroud)


luv*_*ere 6

如果UICollectionView水平滚动,则将其contentSize宽度除以其框架的宽度:

int pages = floor(self.collectionView.contentSize.width /    
                  self.collectionView.frame.size.width) + 1;
Run Code Online (Sandbox Code Playgroud)

如果它垂直滚动,则将其contentSize高度除以其框架的高度:

int pages = floor(self.collectionView.contentSize.height /    
                  self.collectionView.frame.size.height) + 1;
Run Code Online (Sandbox Code Playgroud)

  • 这假设没有间距,并且所有项目具有相同的宽度或高度. (4认同)
  • 不会使用`ceil`*更准确,因为如果`content.width`和`frame.size.width`相等,你最终得到`2`,当技术上只有一页? (4认同)
  • 难道你不能使用`ceil`而不是'floor`并加1? (2认同)