Jon*_*han 5 text image alignment swiftui
我需要在视图中显示 SF 符号(图像)和文本(作为标题)。由于文本可能很长,我希望它在第二行的图像下方通过。
预期结果(几乎!):
我首先尝试HStack
使用图像和文本。但文本不会位于图像下方:第二行以左侧“填充”(对应于左侧图像空间)开始。
所以我做了这段代码(以获得之前的屏幕截图):
HStack(alignment:.top) {
Text(Image(systemName: "circle.hexagongrid.circle"))
.font(.caption)
.foregroundColor(.pink)
+
Text("A long text as example")
.font(.title2).bold()
.foregroundColor(.pink)
}
.frame(width:140)
Run Code Online (Sandbox Code Playgroud)
但我想将图像与第一行的中心对齐。图像中心应垂直位于 顶部A
和底部的中间g
。
重要的是我的第二条(以及更多)条线要穿过我的图像下方。而且我不想要更大的图像字体。
首先,您可以删除它,HStack
因为它是多余的。您可以将其替换为括号()
来封装新的Text
,这样您就可以使用更多修饰符,例如设置宽度。
主要的解决方案是使用baselineOffset(_:)
这意味着您可以将图像从 的基线偏移Text
。下面,我们仅偏移1
,但这可以是您想要的任何值(包括十进制数字,例如0.99
)。
代码:
struct ContentView: View {
var body: some View {
(
Text(Image(systemName: "circle.hexagongrid.circle"))
.font(.caption)
.foregroundColor(.pink)
.baselineOffset(1)
+
Text("A long text as example")
.font(.title2)
.bold()
.foregroundColor(.pink)
)
.frame(width: 140)
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
奖励:您可以在 s 组合foregroundColor(.pink)
后移动修改器Text
,因此您不必重复它。
我不知道您是否可以强制图像在所有情况下自动居中,但您可以.baselineOffset()
向文本中的图像添加修饰符,以将图像向上移动固定的量。例如:
\nText(Image(systemName: "circle.hexagongrid.circle"))\n .font(.caption)\n .foregroundColor(.pink)\n .baselineOffset(3.0)\n+\nText("A long text as example")\n .font(.title2).bold()\n .foregroundColor(.pink)\n
Run Code Online (Sandbox Code Playgroud)\n一旦您找到了默认文本大小的正确偏移量,您就可以通过使偏移大小相对于基本大小来适应可访问性变化,例如
\nStruct MyView: View {\n @ScaledMetric(relativeTo: .title2) var baselineOffset: CGFloat = 3.0\n\n // and in your body\xe2\x80\xa6\n .baselineOffset(baselineOffset)\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
4569 次 |
最近记录: |