我的UICollectionView中嵌入了一个UIPageControl。每个页面都有自己的指定页面,我将其拆分成集合视图单元格。当我滑动到第二页时,页面控制指示器保持为1,而当我滑动到第三页时,它会正确地更新为第三个指示器。当我滑动回到第2页时,页面控件现在显示了正确的指示器。这种情况每次都会发生,只在第二页发生。
下面是我的一些代码:
在具有集合视图的主控制器上,
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellId", forIndexPath: indexPath) as! ItemImageCell
if let imageURL = self.featuredItem.itemImageNames {
cell.itemImageURL = imageURL[indexPath.item]
cell.pageControl.currentPage = indexPath.item
cell.pageControl.numberOfPages = imageURL.count
}
return cell
}在cellView类中,
let pageControl: UIPageControl = {
let pageControl = UIPageControl()
pageControl.pageIndicatorTintColor = UIColor.grayColor()
pageControl.currentPageIndicatorTintColor = UIColor.blackColor()
return pageControl
}()
override func setupViews() {
backgroundColor = UIColor.whiteColor()
addSubview(pageControl)
addConstraint(NSLayoutConstraint(item: pageControl, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0))
}我没有正确地设置它吗?
编辑:
featuredItem模型类:
class FeaturedItem: NSObject {
var itemImageNames: [String]?
var itemTitle: String?
var itemHighlight: String?
var itemDescription: String?
var itemURL: String?
}发布于 2016-08-17 08:54:27
由于您的self.featuredItem.itemImageNames最初可能为空,因此页面控件可能未正确设置。您可以在重新加载数据后尝试重新加载集合视图
但是,数据源方法cellForItemAtIndexPath可能不适合更新页面指示器;当集合视图需要单元格时,不一定在显示单元格时调用该方法。它可以在用户滚动之前调用,以便预取单元格,或者当用户滚动时,如果集合视图已经缓存了该单元格,则不会调用它(例如,快速左/右/左滚动)。
您应该在委托方法willDisplayCell:forItemAtIndexPath:中更新页面指示器
func collectionView(collectionView: UICollectionView,
willDisplayCell cell: UICollectionViewCell,
forItemAtIndexPath indexPath: NSIndexPath) {
guard let myCell = cell as? ItemImageCell,
imageURL = self.featuredItem.itemImageNames else {
return
}
myCell.pageControl.currentPage = indexPath.item
myCell.pageControl.numberOfPages = imageURL.count
}发布于 2016-08-17 11:38:05
在这篇文章中,我找到了我的问题的解决方案。
Why is not updated currentPage indicator on UIPageControl?
具体地说,我使用来自paulw11的解决方案的建议,将我当前的cellForItemAtIndexPath实现更改为以下内容:
func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
guard let myCell = cell as? ItemImageCell, imageURL = self.featuredItem.itemImageNames else {
return
}
myCell.pageControl.numberOfPages = imageURL.count
myCell.pageControl.currentPage = indexPath.item
}以及在设置currentPage变量之前设置numberOfPages变量。
发布于 2019-04-05 08:32:03
实际上,解决方案非常简单。您需要先分配numberOfPages,然后再分配currentPage。
所以把它们翻过来就行了。
https://stackoverflow.com/questions/38984457
复制相似问题