1

I am working on a macOS media player with SwiftUI. I want my window resized to preset or calculated size, when a new video is loaded. Then user could resize the window with a fixed aspect ratio.

I tried

  1. .frame maxHeight/maxWidth it has no effect. The height and width param has created a fixed size window.
  2. Onchange function could detect the change of height or width when use together with GeometryReader but the inner frame could not fit the outside window.

I could somehow resize the window and then let user resize the window as they wish. But I could not keep the UI in preset aspect ratio.

My simplified code as follow:

struct ContentView: View {
    
    @ObservedObject var playerModel : PlayerModel
    
    var body: some View {
        
        VideoPlayer(  player: playerModel.player)
            .fileImporter(isPresented: $playerModel.Openfile, allowedContentTypes: [UTType.movie]) {  (res) in
                do {
                    let fileUrl = try res.get()
                    
                    ResizeToAsset (asset size)
                } catch{
                    print ("error reading")
                }
            }
            .frame(minWidth: playerModel.maxWidth,maxWidth: playerModel.maxWidth ,minHeight: playerModel.minHeight,maxHeight: playerModel.maxHeight  )
    }
    
}

class PlayerModel: ObservableObject  {
    @Published var player: AVPlayer
    @Published var Openfile : Bool
    @Published var minHeight : CGFloat
    @Published var minWidth : CGFloat
    @Published var maxHeight : CGFloat
    @Published var maxWidth : CGFloat
    
    init() {
        self.player =  AVPlayer()
        Openfile=false
        
        minHeight = 720
        minWidthwidth = 1080
        maxHeight = .infinity
        maxWidth = .infinity
    }
    
    func ResizeToAsset( size : CGSize){
        maxHeight=.infinity
        maxWidth=.infinity
        minHeight=size.height
        minWidth=size.width
    }
}
Philip Mok
  • 269
  • 2
  • 8
  • Does this answer your question https://stackoverflow.com/a/64836292/12299030? Also can be helpful https://stackoverflow.com/a/59387212/12299030 if you use AppDelegate Life Cycle. – Asperi Oct 26 '21 at 13:17
  • How to keep the window in a preset aspect ratio? like something vlc player does? – Philip Mok Oct 26 '21 at 15:12

0 Answers0