英文:
How can I make an SF symbol horizontally align centered in SwiftUI?
问题
我有一个 SwiftUI 图像视图,只显示一个 SF 符号:
```swift
GeometryReader { g in
Image(systemName: "a.square")
.font(.system(size: g.size.width))
}
它呈现如下:
我尝试使用 .multilineTextAlignment(.center)
修改器来将其居中,但没有任何效果。
<details>
<summary>英文:</summary>
I have a SwiftUI Image view that displays only an SF symbol:
GeometryReader { g in
Image(systemName: "a.square")
.font(.system(size: g.size.width))
}
}
It renders like this:
[![Preview of Image view](https://i.stack.imgur.com/aVSKZl.png)](https://i.stack.imgur.com/aVSKZ.png)
I tried modifying the view with the `.multilineTextAlignment(.center)` modifier to center it, and that didn't do anything.
</details>
# 答案1
**得分**: 2
```plaintext
你可以尝试添加以下命令行:
.position(x: g.size.width / 2, y: g.size.width / 2)
你写的代码看起来像这样:
GeometryReader { g in
Image(systemName: "a.square")
.font(.system(size: g.size.width))
.position(x: g.size.width / 2, y: g.size.width / 2)
}
}
英文:
You can try adding this command line for it:
.position(x: g.size.width / 2, y: g.size.width / 2)
The code you wrote looks like this:
GeometryReader { g in
Image(systemName: "a.square")
.font(.system(size: g.size.width))
.position(x: g.size.width / 2, y: g.size.width / 2)
}
}
答案2
得分: 0
为什么不用声明式的方式?
VStack {
Image(systemName: "a.square")
.resizable()
.aspectRatio(1.0, contentMode: .fit)
.padding()
Spacer()
}
英文:
Why not the declarative way?
VStack {
Image(systemName: "a.square")
.resizable()
.aspectRatio(1.0, contentMode: .fit)
.padding()
Spacer()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论