如何让 Text 中的文本内容自动进行调整

在 SwiftUI 中,使用Text 添加了frame修饰器后文本内容经常出现显示不完整的情况,例如下面的场景:

如果我们希望在指定控件的范围内让文本内容尽可能地显示完整,我们可以给Text添加 minimumScaleFactor修饰器,即设置Text最小比例因子。它的作用就是指定文本内容能按照设定的font原始尺寸缩小的最小比例,从而让文本内容尽可能的显示完整。例如:

1
2
3
4
5
6
7
8
9
10
VStack(spacing:20) {
Text("Swift is a powerful and intuitive programming language for all Apple platforms. It’s easy to get started using Swift, with a concise-yet-expressive syntax and modern features you’ll love. Swift code is safe by design and produces software that runs lightning-fast.")
.font(.headline)

Text("Swift is a powerful and intuitive programming language for all Apple platforms. It’s easy to get started using Swift, with a concise-yet-expressive syntax and modern features you’ll love. Swift code is safe by design and produces software that runs lightning-fast.")
.font(.headline)
.minimumScaleFactor(0.5)
}
.padding()
.frame(height: 200)

因为我们给HStack设置了frame,并把高度限制为200,所以在这个高度范围内是无法完整显示两个Text内容的。如果不给最后一个Text设置minimumScaleFator,它展示的效果如下:

设置后的效果如下:

通过前后两种效果的比较我们可以发现,在设置了minimumScaleFactor0.5后,后一个Text的字体大小在原来设置的font(.headline)的基础上进行缩小操作。

注意,它并不是缩小为原来尺寸的0.5,它只是在能显示完整内容的基础上进行了缩小,只是我们设定了最小能缩小的值为原来的0.5

当我们把HStackframeheight设置能完整显示两个Text时,字体就不会进行缩放了。

1
.frame(height: 500)

同样地,如果把height设置的很小,后一个文本字体最小能缩放的范围也只是原来的0.5.

1
.frame(height: 100)

如果把minimumScaleFactor设置为 0.1,它就可以缩的更小。