仅在可见单元格上播放视频

时间:2016-04-06 15:08:01

标签: ios swift uitableview avplayer

我怎样才能播放可见细胞的视频? 单元格不可见后停止播放视频?

我知道这与indexPathsForVisibleRows有关但有问题如何实现它

目前一次看到Cell。

.......

import UIKit
import AVKit
import AVFoundation

class videoDevTable: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return 3
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! VideoTableViewCell

    let videoURL = NSURL(string: "https://scontent.cdninstagram.com/t50.2886-16/12951809_1538642766431783_2068695559_n.mp4")
    let player = AVPlayer(URL: videoURL!)

    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = cell.playerView.bounds

    cell.playerView.layer.addSublayer(playerLayer)
    player.play()

    return cell
}

1 个答案:

答案 0 :(得分:0)

我开发了类似的内容,将view(带视频)添加到自定义单元格,并调用 - updateVisibility方法 - didScroll tableView

代表

假设此处的self是您带视频的视图

    - (void)updateVisibilityInScrollView:(UIScrollView*)scrollView
    {
        if (!self.superview) {
            return;
        }
    // Get rect of video relative to scrollView (which is tableView)
        CGRect relativeToScrollViewRect = [self convertRect:self.bounds toView:scrollView];
// get visible scrollView rect
        CGRect visibleScrollViewRect = CGRectMake(scrollView.contentOffset.x, scrollView.contentOffset.y, scrollView.bounds.size.width, scrollView.bounds.size.height);

        if ([self moreThenHalfOfRect:relativeToScrollViewRect visibleInRect:visibleScrollViewRect]) {
            // visible half - resume
        } else {
            // supposed to be paused
        }
    }


- (BOOL)moreThenHalfOfRect:(CGRect)rect visibleInRect:(CGRect)visibleRect
{
    return (CGRectContainsPoint(visibleRect, CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect))));
}

Ofcaurce,您可以修改以显示完全可见细胞的视频

抱歉,我刚刚复制了我的解决方案(没有swift示例)。