您的位置:首页 > 移动开发

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

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

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

- (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中,自动去播放其中的视频:

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


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

- (void)videoPlayListTableViewCellPlayButtonTappedWithIndex:(NSInteger)index AndCell:(SCVideoPlayListTableViewCell *)cell
{
if(_currentPlayingCell){
[_currentPlayingCell backToInitState];
_currentPlayingCell = nil;
}
_currentPlayingIndex = index;
_currentPlayingCell = cell;
}


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

- (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];
}


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

- (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中的视频

- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
if(_currentPlayingCell){
[_currentPlayingCell backToInitState];
_currentPlayingCell = nil;
}
}


OK,大功告成。

PS:项目完整版下载地址为:

https://github.com/wangqi211/VideoListPlayDemo
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  视频 搜狐 uitableview