如何在Swift中调整AVPlayer的宽度和高度

时间:2018-10-31 08:57:33

标签: ios swift swift4 avplayer

我正在使用AVKit播放url中的视频,并且该视频正在播放,没有任何问题。我创建了一个PlayerViewClass,将播放器分配给该视图。

PlayerViewClass.swift

import UIKit
import AVKit
import AVFoundation


class PlayerViewClass: UIView {

override static var layerClass: AnyClass {

    return AVPlayerLayer.self
}

var playerLayer: AVPlayerLayer {
    return layer as! AVPlayerLayer
}

var player: AVPlayer? {
    get {
        return playerLayer.player
    }

    set {
        playerLayer.player = newValue
    }
}

}

然后我在cellForItemAt的{​​{1}}方法中使用了它

ViewController

我不知道如何将播放器的大小调整为整个func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "videoCell", for: indexPath) as? VideoCollectionCell else { return UICollectionViewCell() } let videoUrl = URL(string: "file.mp4") let avPlayer = AVPlayer(url: videoUrl!) cell.playerView.playerLayer.player = avPlayer cell.playerView.frame = CGRect(x: 0, y: 0, width: 352, height: 180) // it is not resizing cell.playerView.player?.play() return cell } 单元格的高度和宽度:-

myCell

CollectionViewCell 类:-

CGSize(width: 352, height: 180)

请帮助。

2 个答案:

答案 0 :(得分:1)

代码错误。每个视图都有一个图层。

虽然它的层是CALayer,而不是AVPlayerLayer。

class PlayerViewClass: UIView {

override static var layerClass: AnyClass {

    return AVPlayerLayer.self
}

var playerLayer: AVPlayerLayer {
    return layer as! AVPlayerLayer
}

您正在使用CGRect

cell.playerView.frame= CGRect(x: 0, y: 0, width: 352, height: 180)

这是CGSize

CGSize(width: 352, height: 180)

enter image description here

答案 1 :(得分:0)

尝试一下:-

extension yourViewController : UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView,
        layout collectionViewLayout: UICollectionViewLayout,
        sizeForItemAt indexPath: IndexPath) -> CGSize {
        // your code here
        //width and height as per your requirement
        return CGSize(width: yourWidth, height: yourHeight)
    }
}

我希望这会对您有所帮助, 谢谢。