无法使用 SwiftUI 使自定义 UIView 方面比例适合/填充 [英] Trouble to make a custom UIView aspect scale fit/fill with SwiftUI

查看:25
本文介绍了无法使用 SwiftUI 使自定义 UIView 方面比例适合/填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SwiftUI 中没有公共 API 来响应 View 协议的可调整大小的修饰符.只有 SwiftUI 中的 Image 可以与 .resizable() 一起使用.像 UIView for GIF 这样的自定义 UIView 现在无法调整大小.

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.

我使用 SDWebImageSwiftUI AnimatedImage,它支持 UIKit 视图 SDAnimatedImageView.AnimatedImage 不响应 .resizable()、.scaleToFit、.aspectRatio(contentMode: .fit) 等.WebImage 支持 SwiftUI Image,所以它工作正常.

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)
        }
    }
}

不确定是否是 Apple 的错误.期望像 SDWebImageSwiftUI AnimatedImage 这样的自定义视图响应 SwiftUI 大小相关的修饰符,如 .scaledToFit().

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

相关问题:https://github.com/SDWebImage/SDWebImageSwiftUI/issues/3

推荐答案

SwiftUI 使用抗压缩优先级和内容拥抱优先级来决定可以调整什么大小.

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.

示例:

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

这将允许您将 .frame(width:height:) 设置为您想要的任何大小.

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

这篇关于无法使用 SwiftUI 使自定义 UIView 方面比例适合/填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆