英文:
SwiftUI: specifying the minimum width of a .background Capsule
问题
我正在学习SwiftUI,并尝试创建一个简单的徽章视图(即,在胶囊内部的文本)。我还希望确保胶囊的宽度至少与其高度一样。
以下代码大部分是有效的,除了文本未居中在胶囊内。
如果没有几何读取器,我可以删除.frame
,但如果文本很短,最终会得到一个太窄的胶囊。或者,我可以包括一个具有minWidth
设置为常数的框架,但这不会对任何类型的自适应布局产生良好的响应。
我正在寻找计算最小宽度的另一种方法,或者一种确保文本居中在嵌套在几何读取器中的胶囊中的方法,但是一直没有找到正确的方法。
import Foundation
import SwiftUI
struct Badge: View {
let text: String
var body: some View {
Text(verbatim: text)
.font(.caption2)
.foregroundColor(.white)
.padding(2)
.border(.black.opacity(0.25))
.background {
GeometryReader { proxy in
Capsule()
.fill(.red)
.frame(minWidth: proxy.size.height)
}
}
}
}
struct Badge_previews: PreviewProvider {
static var previews: some View {
HStack(spacing: 30) {
Badge(text: "1")
Badge(text: "10")
Badge(text: "100")
Badge(text: "1000")
}
}
}
英文:
I'm learning SwiftUI and trying to create a simple badge view (i.e., text inside a capsule). I also want to ensure that the capsule is at least as wide as it is high.
The following mostly works, except that the text is not centered in the capsule.
Without the geometry reader I can either drop the .frame
but end up with a capsule that is too narrow if the text is short. Or, I can include the frame with minWidth
set to a constant, but that won't respond well to any kind of adaptive layout.
I am looking for either another approach to calculating the minimum width, or a way to ensure that the text is centered in the capsule embedded in a geometry reader, but haven't been able to find the correct incantation.
import Foundation
import SwiftUI
struct Badge: View {
let text: String
var body: some View {
Text(verbatim: text)
.font(.caption2)
.foregroundColor(.white)
.padding(2)
.border(.black.opacity(0.25))
.background {
GeometryReader { proxy in
Capsule()
.fill(.red)
.frame(minWidth: proxy.size.height)
}
}
}
}
struct Badge_previews: PreviewProvider {
static var previews: some View {
HStack(spacing: 30) {
Badge(text: "1")
Badge(text: "10")
Badge(text: "100")
Badge(text: "1000")
}
}
}
答案1
得分: 0
我能够通过为胶囊指定一个负的 x 偏移来解决这个问题,如果文本的高度超过了宽度。具体地说:
GeometryReader { proxy in
Capsule()
.fill(.red)
.frame(minWidth: proxy.size.height)
.offset(
x: proxy.size.width >= proxy.size.height ?
0 : -(proxy.size.height - proxy.size.width) / 2
)
}
英文:
I was able to solve this by using specifying a negative x offset for the capsule if the text's height exceeds its width. Specifically:
GeometryReader { proxy in
Capsule()
.fill(.red)
.frame(minWidth: proxy.size.height)
.offset(
x: proxy.size.width >= proxy.size.height ?
0 : -(proxy.size.height - proxy.size.width) / 2
)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论