视频列表自动播放方案

视频cell滑动时自动播放,实现起来主要是获取滚动时刻的cell的frame,IGListScrollDelegatelistAdapter(_:didEndDragging:willDecelerate:) 获取可见cell,播放符合规则的视频cell,并暂停其余cell。

主要记录思路,供大家参考。规则如下:

  • 视频frame超过一半在Screen上的最前面的cell
  • 少于一半则停止播放,以导航栏底部64为准线
  • vc appear 手动调用此方法
  • vc didMove(toParentViewController:) release player
  • visibleCells 方法返回 cell indexPath 不是顺序的,是个坑,要重新排序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
extension VideoSectionController: IGListScrollDelegate {

// MARK: - GListScrollDelegate

func listAdapter(_ listAdapter: IGListAdapter!, didScroll sectionController: IGListSectionController!) {

}

func listAdapter(_ listAdapter: IGListAdapter!, willBeginDragging sectionController: IGListSectionController!) {

}

func listAdapter(_ listAdapter: IGListAdapter!, didEndDragging sectionController: IGListSectionController!, willDecelerate decelerate: Bool) {

guard var cells = self.collectionContext?.visibleCells(for: sectionController) as? [VideoCell] else { return }

// cells 重新排序
cells = cells.sorted { (cell0, cell1) -> Bool in
guard let indexPath0 = collectionContext?.index(for: cell0, sectionController: sectionController) else {
return true
}
guard let indexPath1 = collectionContext?.index(for: cell1, sectionController: sectionController) else {
return true
}

if indexPath0 < indexPath1 {
return true
} else {
return false
}

}

for cell in cells {

let videoCenter = cell.convert(cell.videoCoverImageView.center, to: nil)

if videoCenter.y < 64 {
// pause
cell.pause()
} else {
// play
cell.play()
break
}
}

}
}
1
2
3
4
5
6
7
8
override func didMove(toParentViewController parent: UIViewController?) {
super.didMove(toParentViewController: parent)

if parent == self.navigationController?.parent {
print("Back tapped")
NotificationCenter.default.post(name: Notification.Name.VideoPlayer.VideoCellStopPlay, object: nil, userInfo: nil)
}
}