我有一个UIPageControl嵌入我的UICollectionView的情况。每个页面都有自己的指定页面,我已将其拆分为收集视图单元格。当我向第二页滑动时,页面控制指示器保持在1,当我滑动到第3页时,它正确地更新到第3个指示器。当我滑动,返回第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?
}
答案 0 :(得分:0)
由于您的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
}
答案 1 :(得分:0)
我能够在另一篇文章中找到我的问题的解决方案。
Why is not updated currentPage indicator on UIPageControl?
具体来说,我使用Paulw11解决方案的建议将我当前的cellForItemAtIndexPath实现更改为以下内容:
INSERT INTO `identity` () VALUES()
并在设置currentPage变量之前设置numberOfPages变量。
答案 2 :(得分:0)
实际上,解决方案非常简单。 您需要先分配numberOfPages,然后再分配currentPage。
所以将它们翻转过来就可以了。