UIViewRepresentable will not be displayed without explicit specification of the view size

I'm trying to wrap PHLivePhotoView with UIViewRepresentable. When I put the view in ScrollView, its height gets close to zero. I have to explicit the view size with frame(width:height:) modifier to make it visible.

( When I put it in VStack, it will displayed correctly. )

import SwiftUI
import PhotosUI

struct LivePhotoView: UIViewRepresentable {
    let livePhoto: PHLivePhoto

    func makeUIView(context: Context) -> PHLivePhotoView {
        return PHLivePhotoView(frame: .zero)
    }
    
    func updateUIView(_ livePhotoView: PHLivePhotoView, context: Context) {
        livePhotoView.livePhoto = livePhoto
    }
}
import SwiftUI
import PhotoKit

struct ContentView: View {
    @Binding var photos:[PHLivePhoto] = []
    
    var body: some View {
        ScrollView { //👈🏼
            ForEach(photos, id: \.self) { photo in 
                PHLivePhotoView(livePhoto: photo)
            }
        }
    }
}

How can I make LivePhotoView work without size specification, like SwiftUI.Image ?

Answered by Harumaru169 in 683262022

Self-solved.

import SwiftUI
import PhotosUI

struct LivePhotoView: View {
    let livePhoto: PHLivePhoto
    
    var body: some View {
        _LivePhotoView(livePhoto: livePhoto)
            .aspectRatio(livePhoto.size.width / livePhoto.size.height, contentMode: .fill)
    }
}

struct _LivePhotoView: UIViewRepresentable {
    let livePhoto: PHLivePhoto
    
    func makeUIView(context: Context) -> PHLivePhotoView {
        let livePhotoView = PHLivePhotoView(frame: .zero)
        livePhotoView.livePhoto = livePhoto
        return livePhotoView
    }
    
    func updateUIView(_ livePhotoView: PHLivePhotoView, context: Context) {
    }
}
Accepted Answer

Self-solved.

import SwiftUI
import PhotosUI

struct LivePhotoView: View {
    let livePhoto: PHLivePhoto
    
    var body: some View {
        _LivePhotoView(livePhoto: livePhoto)
            .aspectRatio(livePhoto.size.width / livePhoto.size.height, contentMode: .fill)
    }
}

struct _LivePhotoView: UIViewRepresentable {
    let livePhoto: PHLivePhoto
    
    func makeUIView(context: Context) -> PHLivePhotoView {
        let livePhotoView = PHLivePhotoView(frame: .zero)
        livePhotoView.livePhoto = livePhoto
        return livePhotoView
    }
    
    func updateUIView(_ livePhotoView: PHLivePhotoView, context: Context) {
    }
}
UIViewRepresentable will not be displayed without explicit specification of the view size
 
 
Q