UIImageView 可表示未调整大小

san*_*.gs 7 swiftui uiviewrepresentable

I can't find a way to make a UIImageView wrapped in a UIViewRepresentable be sized to fit the frame. It always resizes beyond the screen no matter what content Mode or clipping or explcit framing I do. (The image dimensions are much larger than the device screen frame)

To clarify: I need to use UIImageView due to some subview positioning I have to do down the line and various other reasons.

Here's a paired down example:

struct ImageView: UIViewRepresentable {
    
    var image: UIImage
    
    func makeUIView(context: Context) -> some UIView {
    
        let imageView = UIImageView()
        imageView.image = image
        imageView.backgroundColor = .red
        imageView.contentMode = .scaleAspectFit
        imageView.clipsToBounds = true
        imageView.frame = CGRect(x: 0, y: 0, width: 300, height: 400)
        
        return imageView
    }
    
    func updateUIView(_ uiView: UIViewType, context: Context) {
    }
    
}
Run Code Online (Sandbox Code Playgroud)

Then this is how I'm trying to implement it

struct ContentView: View {
    var body: some View {
        ImageView(image: UIImage(named: "full-ux-bg-image")!)
        //.frame(width: 300, height: 400, alignment: .center)  //This is just a test of explicit sizing
            .padding()
    }
}
Run Code Online (Sandbox Code Playgroud)

Any ideas how to make this work? I want it to fit in the SwiftUI view without going over.

Asp*_*eri 13

它对内容拥抱/压缩有默认的约束,为了能够在外部操作视图,我们需要降低这些约束(......并且永远不要设置可表示的框架,以防万一)

这是固定变体(使用 Xcode 14 / iOS 16 测试)

func makeUIView(context: Context) -> some UIView {

    let imageView = UIImageView()
    imageView.image = image
    imageView.backgroundColor = .red
    imageView.contentMode = .scaleAspectFit
    imageView.clipsToBounds = true
    
    imageView.setContentHuggingPriority(.defaultLow, for: .vertical)
    imageView.setContentHuggingPriority(.defaultLow, for: .horizontal)
    imageView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
    imageView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)

    return imageView
}
Run Code Online (Sandbox Code Playgroud)