iOS6 UICollectionView和UIPageControl - 如何获取可见单元格? [英] iOS6 UICollectionView and UIPageControl - How to get visible cell?

查看:797
本文介绍了iOS6 UICollectionView和UIPageControl - 如何获取可见单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在研究iOS6新功能时,我遇到了一个关于 UICollectionView

我目前正在使用Flow布局测试它,滚动方向设置为水平,滚动和分页启用。我已将其大小设置为与我的自定义单元格完全相同,因此它可以一次显示一个,并通过向侧面滚动,用户将看到其他现有单元格。

While studying iOS6 new features I got a question about UICollectionView.
I am currently testing it with Flow layout and the scroll direction set to horizontal, scrolling and paging enabled. I've set its size to exactly the same as my custom's cells, so it can show one at a time, and by scrollig it sideways, the user would see the other existing cells.

完美无缺。

现在我要添加 UIPageControl 到我制作的集合视图,因此它可以显示哪个单元格可见以及有多少单元格就在那里。

Now I want to add and UIPageControl to the collection view I made, so it can show up which cell is visible and how many cells are there.

构建页面控件相当简单,定义了frame和numberOfPages。

Building up the page control was rather simple, frame and numberOfPages defined.

问题我正在问题标题是如何在集合视图中获取当前可见的单元格,因此它可以更改页面控件的当前页面。

The problem I am having, as the question titles marks, is how to get which cell is currently visible in the collection view, so it can change the currentPage of the page control.

我已经尝试过委托方法,比如cellForItemAtIndexPath,但它是为了加载单元格而不是显示它们。当一个单元格不再显示时,didEndDisplayingCell触发,这是我需要的相反事件。

I've tried delegate methods, like cellForItemAtIndexPath, but it is made to load cells, not show them. didEndDisplayingCell triggers when a cell its not displayed anymore, the opposite event of what I need.

似乎-visibleCells和-indexPathsForVisibleItems,集合视图方法,是正确的选择对我来说,但我碰到了另一个问题。什么时候触发它们?

Its seems that -visibleCells and -indexPathsForVisibleItems, collection view methods, are the correct choice for me, but I bumped into another problem. When to trigger them?

提前谢谢,希望我能让自己清楚明白,这样你们才能理解我!

Thanks in advance, hope I made myself clear enough so you guys can understand me!

推荐答案

您必须将自己设置为 UIScrollViewDelegate 并实现 scrollViewDidEndDecelerating:方法像这样:

You must setup yourself as UIScrollViewDelegate and implement the scrollViewDidEndDecelerating:method like so:

Objective-C

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

Swift

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

    let pageWidth = self.collectionView.frame.size.width
    pageControl.currentPage = Int(self.collectionView.contentOffset.x / pageWidth)
}

这篇关于iOS6 UICollectionView和UIPageControl - 如何获取可见单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆