代码之家  ›  专栏  ›  技术社区  ›  Wings

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

  •  0
  • Wings  · 技术社区  · 7 年前

    我在用 AVKit 从url播放视频,视频播放没有任何问题。我创造了一个 PlayerViewClass 将玩家指定给视图。

    PlayerViewClass。敏捷的

    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 我的方法 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 高度和宽度:-

    CGSize(width: 352, height: 180)
    

    CollectionViewCell 课程:-

    class VideoCollectionCell: UICollectionViewCell {
    
    @IBOutlet weak var playerView: PlayerViewClass!
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
    
    }
    }
    

    请帮忙。

    2 回复  |  直到 7 年前
        1
  •  1
  •   dengApro    7 年前

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

    而它的图层是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

        2
  •  0
  •   V D Purohit Niki Trivedi    7 年前

    试试这个:-

    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)
        }
    }
    

    我希望这对你有帮助, 谢谢