【发布时间】:2018-05-25 00:29:20
【问题描述】:
我有一个包含 collectionView 的视图控制器:
class TagViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return posts.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let post = posts[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! SNPostViewCell
cell.isVideo = post.isVideo
cell.mediaURL = URL(string: post.mediaURL)
cell.backgroundColor = UIColor.black
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let post = posts[indexPath.row]
if post.isVideo == true {
self.performSegue(withIdentifier: "playVideo", sender: nil)
} else {
print("is image. might go full screen one day here")
}
let bin = self.bins[post.timeStamp]
print(bin)
}
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { //Error: method cannot override from its superclass
<#code#>
}
}
虽然我可以覆盖那些 collectionView 函数,但似乎要覆盖 scrollViewDidEndDecelerating 我特别需要一个 collectionView 的实例(而不是在视图控制器中这样做)
好的,所以我创建了一个继承自 collectionViewController 的自定义 collectionView。这会正确覆盖 scrollViewDidEndDecelerating(该方法现在确实覆盖了它的超类),并且我正在使用其中的代码来查找当前单元格的索引,
class PagingCollectionViewController: UICollectionViewController {
...
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if (self.collectionView.contentOffset.y < 0) {
self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.x, 0.0);
}
for cell in yourCollectionViewname.visibleCells() as [UICollectionViewCell] {
let indexPath = yourCollectionViewname.indexPathForCell(cell as UICollectionViewCell)
}
}
...
}
但是,正如您所见,这需要引用我不会在类中定义的 collectionView 的当前索引,对吗?仅在创建和填充实例的视图控制器中...
所以我真的不明白在哪里放置这个覆盖 scrollViewDidEndDecelerating 函数以及如何成功访问其中的数据 - 以查找索引。
【问题讨论】:
-
对不起,我有点困惑。你的问题到底是什么?它是如何实现滚动视图委托方法的?将这些方法放在哪里?是如何从这些方法中获取对集合视图的引用?
标签: ios swift uiscrollview uicollectionview