我做了什么: -
我添加了在单元格完全可见时播放视频的代码 当我向下或向上滚动它再次重新加载tableview并播放 再次视频。但是,我的要求是不同的。
我真正想要的是什么:
我想播放视频,直到完全向后或向前的单元格 可见。当用户向下滚动或向上滚动时,它不会影响直到 向后或向前的细胞完全可见。
设计
0
编码:
VideoTableCell.h
Table Cell Layout Description
-> Video Table Cell (Fix height 393)
-> Content View
-> Main view - (as per Content view of Table view Cell)
-> Title View (0, 0, MainView.width, 57)
-> Video View (0, 57, MainView.width, 200);
-> Description View (0, 257, MainView.width, 136)
VideoTableCell.m
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface VideoTableCell : UITableViewCell
@property (strong, nonatomic) IBOutlet UIView *viewForVideo;
@property (strong, nonatomic) IBOutlet UIImageView *imgThumb;
@property (strong, nonatomic) IBOutlet UIButton *btnPlay;
@property (strong, nonatomic) AVPlayerItem* videoItem;
@property (strong, nonatomic) AVPlayer* videoPlayer;
@property (strong, nonatomic) AVPlayerLayer* avLayer;
@end
VideoVC.h
#import "VideoTableCell.h"
@implementation VideoTableCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
return self;
}
- (void)layoutSubviews
{
[super layoutSubviews];
[self.avLayer setFrame:CGRectMake(self.viewForVideo.frame.origin.x, self.viewForVideo.frame.origin.y, self.viewForVideo.frame.size.width, self.viewForVideo.frame.size.height)];
}
@end
VideoVC.m
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface VideoVC : UIViewController <UITableViewDataSource, UITableViewDelegate>
@property (strong, nonatomic) IBOutlet UITableView *tblData;
@end
答案 0 :(得分:15)
每个UITableViewCell
子类都有一个方法prepareForReuse:
,所以在VideoTableCell
中添加一个方法:
-(void)prepareForReuse {
[super prepareForReuse];
[self.videoPlayer play];
}
在您的控制器中实现委托方法:- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
[cell stopVideo];
}
并在stopVideo
中添加[self.videoPlayer pause]
或[cell.videoPlayer stop]
答案 1 :(得分:5)
在UITableView
中尝试此方法func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
// stop video
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
// play video
}
应该帮助你。
如果这不能完全满足您的要求,请尝试覆盖scrollViewDidScroll
more details there
答案 2 :(得分:-2)
为UITableViewCell编写一个类别,以检查单元格是否完全可见:
-(BOOL) isFullyVisible {
UITableView *tableview = (UITableView *)[self parents:[UITableView class]];
CGRect rect = [tableview rectForRowAtIndexPath:[tableview indexPathForCell:self]];
rect = [tableview convertRect:rect toView:tableview.superview];
return CGRectContainsRect(tableview.frame, rect);
}
在 cellForRowAtIndexpath:中检查单元格是否完全可见。如果单元格完全可见则播放视频,否则停止/暂停。