Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble to make a custom UIView aspect scale fit/fill with SwiftUI

Tags:

swiftui

No Public API in SwiftUI to response for the resizable modifier of View protocol. Only Image in SwiftUI could work with .resizable(). Custom UIView like UIView for GIF is not resizable now.

I use SDWebImageSwiftUI AnimatedImage, which is backing UIKit View SDAnimatedImageView. AnimatedImage is not response to .resizable(), .scaleToFit, .aspectRatio(contentMode: .fit), etc. WebImage is backing SwiftUI Image, so it's working fine.

import SwiftUI
import SDWebImageSwiftUI

struct ContentView: View {
    let url = URL(string: "https://media.giphy.com/media/H62DGtBRwgbrxWXh6t/giphy.gif")!
    var body: some View {
        VStack {
            AnimatedImage(url: url)
                .scaledToFit()
                .frame(width: 100, height: 100)
            WebImage(url: url)
                .scaledToFit()
                .frame(width: 100, height: 100)
        }
    }
}

Not sure if it's an Apple bug. Expect custom view like SDWebImageSwiftUI AnimatedImage is responsive to SwiftUI size related modifiers like .scaledToFit().

Related issue: https://github.com/SDWebImage/SDWebImageSwiftUI/issues/3

like image 740
Maundytime Avatar asked Sep 17 '25 07:09

Maundytime


1 Answers

SwiftUI uses the compression resistance priority and the content hugging priority to decide what resizing is possible.

If you want to resize a view below its intrinsic content size, you need to reduce the compression resistance priority.

Example:

func makeUIView(context: Context) -> UIView {
    let imageView = UIImageView(image: UIImage(named: "yourImage")!)
    imageView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
    imageView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
    return imageView
}

This will allow you to set .frame(width:height:) to any size you want.

like image 86
Tomáš Linhart Avatar answered Sep 19 '25 14:09

Tomáš Linhart