I am using AVKit
to play a video from url and the video is playing without any issue. I created a PlayerViewClass
to assign player to the view.
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
}
}
}
And I used it in cellForItemAt
method in my 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
}
I don't understand how can I resize my Player to the whole cell myCell
is of height and width:-
CGSize(width: 352, height: 180)
CollectionViewCell class:-
class VideoCollectionCell: UICollectionViewCell {
@IBOutlet weak var playerView: PlayerViewClass!
override func awakeFromNib() {
super.awakeFromNib()
}
}
Please help.
The code is wrong. Every view has a layer.
While it's layer is CALayer , not AVPlayerLayer.
class PlayerViewClass: UIView {
override static var layerClass: AnyClass {
return AVPlayerLayer.self
}
var playerLayer: AVPlayerLayer {
return layer as! AVPlayerLayer
}
You are using CGRect
,
cell.playerView.frame= CGRect(x: 0, y: 0, width: 352, height: 180)
this is CGSize
CGSize(width: 352, height: 180)
Try this:-
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)
}
}
I hope this will help you, thanks.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.