如何根据CollectionViewCell的项目

时间:2016-06-17 12:01:08

标签: ios swift2 uicollectionviewcell uipagecontrol

我的视图层次结构类似于:

TableView-->tableViewCell-->CollectionView-->CollectionViewCell-->imageView

在我的tableViewCell中我有一些其他项目(textView,标签和UIPageControl)所以现在我试图根据CollectionViewCell的项目(与carousel相同)更改PageControl的currentPage但我不知道为什么UIPageControl是不改变它的立场这是我试过的:

override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {

    // here scrollView is my collectionView 
    if scrollView != tableView {
        pagerControll.currentPage = Int(scrollView.contentOffset.x / self.view.frame.size.width)
    }
}

我也尝试了这个(在滚动浏览tableView后记住单元格中Item的当前位置)

override func tableView(tableView: UITableView,
                        willDisplayCell cell: UITableViewCell,
                                        forRowAtIndexPath indexPath: NSIndexPath) {

    guard let cell = cell as? NotesTableViewCell else { return }

    cell.setCollectionViewDataSourceDelegate(self, forRow: indexPath.row)

    cell.collectionViewOffset = storedOffsets[indexPath.row] ?? 0 
        cell.pageControll.currentPage = calculateCurrentPage(storedOffsets[indexPath.row]  ?? 0)

}

上面从一个(contentoffset)数组中获取每一行的contentOffset,这样我就可以显示CollectionViewCell项的先前位置,当tableView重用它时,它对我的​​collectionView单元格的项目工作正常但不适用于我的{ {1}}

UIPageControl

这里有什么问题?或者怎么做?

更新额外代码:

//在我的tableViewCell中         func setCollectionViewDataSourceDelegate         >         (dataSourceDelegate:D,forRow row:Int){

func calculateCurrentPage(offSet : CGFloat) -> Int{

    if offSet >= self.view.frame.size.width && offSet < (self.view.frame.size.width*2) {

        return 1

    }else if offSet >= (self.view.frame.size.width*2)  {

        return 2

    }else {

        return 0
    }
}

//在TableView中

    collectionView.delegate = dataSourceDelegate
    collectionView.dataSource = dataSourceDelegate
    collectionView.tag = row
    collectionView.reloadData()
}

1 个答案:

答案 0 :(得分:1)

检查#1

UICollectionView个实例上设置UICollectionViewDelegate后,您就会收到collectionView的滚动事件的回调。

似乎您可能在以下调用

中错过设置UICollectionViewDelegate
cell.setCollectionViewDataSourceDelegate(self, forRow: indexPath.row)

您是否可以验证您是否正在接收UICollectionView滚动事件的回调?

检查#2

假设您现在正在接收回调,是否可以使用页面索引检查您的逻辑是否正常工作?一个好处是添加一个print语句,它将显示您正在计算的页面索引。

let pageIndex = Int(scrollView.contentOffset.x / self.view.frame.size.width)
print("pageIndex == \(pageIndex)")

检查#3

假设您正在计算它,是否可以检查cell.pageControl是否正确填充了您需要更新的UIPageControl实例。

也许您需要检查IBOutlet个关联?

检查#4

prepareForReuse()内部回调中,您需要确保将pageControl设置为某个初始值,例如0。

在更新pageIndex时添加一个小延迟可能会有效,如果您发现有时会更新的有些不一致,有时甚至不会更新。

希望它有所帮助。