类似搜狐视频App视频列表播放

有些视频App会有一个视频列表播放功能,例如搜狐视频App的热点模块,腾讯视频App的热点模块等。进入此页面会自动播放视频,滑动页面还会自动切换播放视频,同时支持横竖屏切换,确实比较方便。研究了下,实现方法如下。

首先记录下tableview当前展示的所有cell的indexPath:

1
2
3
4
5
6
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
[self addOneIndexPathToVisibleIndexArrayWithValue:indexPath];
}
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
[_visibleIndexArray removeObject:indexPath];
}

然后当页面停止滑动时要判断出需要播放的视频存在于第几个cell中,自动去播放其中的视频:

1
2
3
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
self.currentPlayingIndex = [self getCurrentCellIndexShouldBePlaying];
}

其次还要将此cell回传到ViewController中,在cell中添加delegate方法,注意如果之前有cell已经在播放视频,需要恢复初始状态

1
2
3
4
5
6
7
8
- (void)videoPlayListTableViewCellPlayButtonTappedWithIndex:(NSInteger)index AndCell:(SCVideoPlayListTableViewCell *)cell {
if(_currentPlayingCell){
[_currentPlayingCell backToInitState];
_currentPlayingCell = nil;
}
_currentPlayingIndex = index;
_currentPlayingCell = cell;
}

接着滑动列表停止时,如果之前播放的cell已经滚出屏幕,需要停止播放

1
2
3
4
5
6
7
8
9
10
11
12
13
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
[NSObject cancelPreviousPerformRequestsWithTarget:self];
BOOL isOutOfScreen = [self judgeCurrentFullScreenPlayingCellIfOutOfScreen];
if(isOutOfScreen){
[self rotateToPortrait];
if(_currentPlayingCell){
[_currentPlayingCell removeFromSuperview];
[_currentPlayingCell backToInitState];
_currentPlayingCell = nil;
}
}
self.currentPlayingIndex = [self getCurrentCellIndexShouldBePlaying];
}

然后为了实现横竖屏切换,添加监测屏幕方向变化的通知,并实现对应的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationHasChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
}
- (void)orientationHasChange:(NSNotification *)notification
{
if(!_currentPlayingCell){
return;
}
UIDevice *device = (UIDevice *)notification.object;
if(device.orientation == UIInterfaceOrientationLandscapeLeft){
[self rotateToLandscapeLeft];
}
else if(device.orientation == UIInterfaceOrientationLandscapeRight){
[self rotateToLandscapeRight];
}
else if(device.orientation == UIInterfaceOrientationPortrait){
[self rotateToPortrait];
}
}

最后要注意,离开页面时也要停止播放当前cell中的视频

1
2
3
4
5
6
7
8
9
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
if(_currentPlayingCell){
[_currentPlayingCell backToInitState];
_currentPlayingCell = nil;
}
}

项目完整版地址请猛戳这里