I have a following simple code to present a video on the screen. This or similar can be found on any tutorial there is about using AVplayer
from UISwift.
struct PlayerView: UIViewRepresentable {
func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PlayerView>) {
}
func makeUIView(context: Context) -> UIView {
return PlayerUIView(frame: .zero)
}
}
class PlayerUIView: UIView {
private let playerLayer = AVPlayerLayer()
override init(frame: CGRect) {
super.init(frame: frame)
let url = Bundle.main.url(forResource: "my_video", withExtension: "mp4")!
let player = AVPlayer(url: url)
player.play()
playerLayer.player = player
layer.addSublayer(playerLayer)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
playerLayer.frame = bounds
}
}
If I put PlayerView
inside an VStack
the view will take as much vertical space as possible based on the sizes of the other views in the stack and then will put the video inside filling it horizontally. So if it is the only view, it will always put the video in the center of the screen and leave margins below and above it. Even if I put spacer after it. Even if I put it inside GeometryReader
.
What I want the view to "hug" the presented video as much as possible, and then bahve as any other SwiftUI view. But I do not understand how SwiftUI does the layout in this case when AVPlayer
inside UIViewRepresentable
is involved.