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

如果我们希望在指定控件的范围内让文本内容尽可能地显示完整,我们可以给Text添加 minimumScaleFactor修饰器,即设置Text的最小比例因子。它的作用就是指定文本内容能按照设定的font原始尺寸缩小的最小比例,从而让文本内容尽可能的显示完整。例如:1
2
3
4
5
6
7
8
9
10VStack(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,它展示的效果如下:

设置后的效果如下:

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




