AVPlayerLayer 仅在边界更改时正确设置

AVPlayerLayer only sets correctly on bounds change

我有一个奇怪的问题。我有一个 table 视图,它的单元格包含一个视频。我将 AVPlayerLayer 设置为拉伸到单元格的大小,但是当 table 视图首次加载时,它不会这样做,只有前 2 个单元格。对于第 3 个单元格,它加载正确,当我从下到上向上滚动 table 视图时,前两个单元格确实加载正确。我创建了一个 13 秒的 youtube 视频来准确显示我的内容意思。请注意视频前几秒前 2 个单元格底部的白色 space。当我向上滚动时,space 不存在,AVPlayerLayer 的边界是正确的。

https://www.youtube.com/watch?v=q7BlZd77QVU

这是我在 cellForRowAtIndexPath:

中设置 tableView 单元格的代码
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentsDirectory = [paths objectAtIndex:0];

  NSString *mov = @".mov";
  NSString *fullComponent = [NSString stringWithFormat: @"%@%@", self.videoChallengeID, mov];
  NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:fullComponent];
  NSURL *url = [NSURL fileURLWithPath:fullPath];

  UIView *blueView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, videoCell.frame.size.width, videoCell.frame.size.height)];
  blueView.backgroundColor = [UIColor blueColor];
  [videoCell.contentView insertSubview:blueView belowSubview:videoCell.bottomView];
  videoCell.item = [AVPlayerItem playerItemWithURL:url];
  self.player = [[AVPlayer alloc] initWithPlayerItem:videoCell.item];
  [self.player setMuted:YES];
  self.player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
  AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
  playerLayer.frame = CGRectMake(0, 0, videoCell.frame.size.width, videoCell.frame.size.height);
  playerLayer.backgroundColor = [UIColor lightGrayColor].CGColor;
  playerLayer.videoGravity = AVLayerVideoGravityResize;
  [blueView.layer addSublayer:playerLayer];
  [self.player play];

我清楚地正确设置了框架,它工作正常,除了加载的前 2 个单元格,第一次加载 table 视图。每隔一段时间它就可以正常工作。知道会发生什么吗?

覆盖

-(void)layoutSubviews {
    [super layoutSubviews]
}

在您的单元格上并设置图层框架

layer.frame = self.bounds

您的单元似乎设置得非常低效,您应该重用视图和图层等内容以获得最佳性能,并只传递您的播放器。

因为第一次实例化单元格时,单元格本身的框架没有设置为它应该的样子。当它们被重用时,没问题,但当它们第一次被实例化时就不行了。

你应该做的是创建一个自定义的 UItableViewCell 子类,然后在 layoutSubviews 函数

中正确设置视频层的帧