【发布时间】:2019-10-20 16:06:48
【问题描述】:
我的目标是确保容器中的文本能够根据其父级进行缩放。当容器只包含一个 Text 视图时效果很好,如下所示:
import SwiftUI
struct FontScalingExperiment: View {
var body: some View {
Text("Hello World ~!")
.font(.system(size: 500))
.minimumScaleFactor(0.01)
.lineLimit(1)
.padding()
.background(
RoundedRectangle(cornerRadius: 20)
.fill(Color.yellow)
.scaledToFill()
)
}
}
struct FontScalingExperiment_Previews: PreviewProvider {
static var previews: some View {
Group {
FontScalingExperiment()
.previewLayout(.fixed(width: 100, height: 100))
FontScalingExperiment()
.previewLayout(.fixed(width: 200, height: 200))
FontScalingExperiment()
.previewLayout(.fixed(width: 300, height: 300))
FontScalingExperiment()
.previewLayout(.fixed(width: 400, height: 400))
}
}
}
结果:
但是,当我们有更复杂的 View 时,我们不能使用相同的方法来根据其父大小自动缩放文本,例如:
import SwiftUI
struct IndicatorExperiment: View {
var body: some View {
VStack {
HStack {
Text("Line 1")
Spacer()
}
Spacer()
VStack {
Text("Line 2")
Text("Line 3")
}
Spacer()
Text("Line 4")
}
.padding()
.background(
RoundedRectangle(cornerRadius: 20)
.fill(Color.yellow)
)
.aspectRatio(1, contentMode: .fit)
}
}
struct IndicatorExperiment_Previews: PreviewProvider {
static var previews: some View {
Group {
IndicatorExperiment()
.previewLayout(.fixed(width: 100, height: 100))
IndicatorExperiment()
.previewLayout(.fixed(width: 200, height: 200))
IndicatorExperiment()
.previewLayout(.fixed(width: 300, height: 300))
IndicatorExperiment()
.previewLayout(.fixed(width: 400, height: 400))
}
}
}
只需添加这 3 个修饰符:
.font(.system(size: 500))
.minimumScaleFactor(0.01)
.lineLimit(1)
不会像第一个例子那样产生结果;文本放大超出框架。
我成功了,使用 GeometryReader 产生了我想要的结果,然后根据geometry.size.width 缩放字体大小。这是在 SwiftUI 中实现预期结果的唯一方法吗?
【问题讨论】:
-
我有您遇到的确切问题,但我无法在任何地方找到答案。在我将视图放入 HStack 之前,一切都按预期工作。您介意与 GeometryReader 分享您的解决方案吗?
-
GeometryReader 为我们提供了框架的高度和宽度,使用这个大小我们可以相应地设置字体。例如:GeometryReader { g in HStack { ... } .font(.system(size: g.size.width / ratio)) } ratio 是任意数字,来调整大小。需要进行手动视觉验证以确保它为您的最小帧正确渲染。
-
您的解决方案运行良好。目视检查是关键。谢谢分享。