如何在SwiftUI中动态调整图像大小以实现可访问性?

如何在SwiftUI中动态调整图像大小以实现可访问性?,swiftui,accessibility,Swiftui,Accessibility,我有一张图片,我正在硬编码大小,但意识到它不适合更大尺寸的类别。如何设置首选尺寸,并让其自动放大到不同尺寸 这就是我的代码的样子: HStack(alignment: .top, spacing: 4) { Text("Some text") Button(action: { showAlert = true }) { Image(systemName: "questionmark.circle.fill")

我有一张图片,我正在硬编码大小,但意识到它不适合更大尺寸的类别。如何设置首选尺寸,并让其自动放大到不同尺寸

这就是我的代码的样子:

HStack(alignment: .top, spacing: 4) {
    Text("Some text")
    Button(action: { showAlert = true }) {
        Image(systemName: "questionmark.circle.fill")
            .resizable()
            .frame(width: 12, height: 12)
            .foregroundColor(.secondary)
    }
}
我还有其他不使用SF符号的场景:

Button(action: action) {
    Label(
        title: {
            Text(title)
                .foregroundColor(Color(.label))
        },
        icon: {
            Image("twitter")
                .resizable()
                .frame(width: 24, height: 24)
        }
    )
}
这是它在不同大小的预览中的外观,但在较大的比例下,图像很小。如何处理此问题以实现可访问性


将代码包装在GeometryReader中

比如说

HStack(alignment: .top, spacing: 4) {
    GeometryReader { geo in 
Text("Some text")
Button(action: { showAlert = true }) {
    Image(systemName: "questionmark.circle.fill")
        .resizable()
        .frame(width: geo.size.width / 9, height: geo.size.height / 9)
        .foregroundColor(.secondary)
     }
}
}

那就去适应任何适合你的


GeometryReader读取当前设备的宽度和高度信息,并允许您进行调整,而不是硬编码。

SwiftUI 2.0为此提供了
ScaleMetric

下面是解决方案的演示。使用Xcode 12.1/iOS 14.1进行测试

普通文本:

最大文本:

struct TestScaledImage:View{

@ScaledMetric var scale:CGFloat=1//哇,太棒了!!这正是我所希望的!!感谢SwiftUI团队和@Asperi指出这一点!!它甚至可以在预览中工作,只是为了提醒一下,以防它对其他人有所帮助..在Xcode 12.3中,我必须做:
@ScaledMetric var imageSize:CGFloat=12
而不是乘法
struct TestScaledImage: View {
    @ScaledMetric var scale: CGFloat = 1     // << here !!
    var body: some View {
        HStack(alignment: .top, spacing: 4) {
            Text("Some text")
            Button(action: {  }) {
                Image(systemName: "questionmark.circle.fill")
                    .resizable()
                    .frame(width: 12 * scale, height: 12 * scale)  // << here !!
                    .foregroundColor(.secondary)
            }
        }
    }
}