如何使用 SwiftUI 缩放文本以适合父视图? [英] How to scale text to fit parent view with SwiftUI?

查看:28
本文介绍了如何使用 SwiftUI 缩放文本以适合父视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在圆形视图中创建一个文本视图.字体大小应自动设置为适合圆圈的大小.这如何在 SwiftUI 中完成?我尝试了 scaledToFill 和 scaledToFit 修饰符,但它们对文本视图没有影响:

I'd like to create a text view inside a circle view. The font size should be automatically set to fit the size of the circle. How can this be done in SwiftUI? I tried scaledToFill and scaledToFit modifiers, but they have no effect on the Text view:

struct ContentView : View {
    var body: some View {
        ZStack {
            Circle().strokeBorder(Color.red, lineWidth: 30)
            Text("Text").scaledToFill()
        }
    }
}

推荐答案

可以使用 GeometryReader 使其在横向模式下也能工作.

One can use GeometryReader in order to make it also work in landscape mode.

首先检查宽度或高度是否较小,然后根据其中较小的值调整字体大小.

It first checks if the width or the height is smaller and then adjusts the font size according to the smaller of these.

GeometryReader{g in
    ZStack {
        Circle().strokeBorder(Color.red, lineWidth: 30)
        Text("Text")
            .font(.system(size: g.size.height > g.size.width ? g.size.width * 0.4: g.size.height * 0.4))
    }
}

这篇关于如何使用 SwiftUI 缩放文本以适合父视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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