简体   繁体   English

如何使一个项目与 HStack 中的其他项目完全位于 HStack 的中心

[英]How to keep an item exactly in the center of an HStack with other items in the HStack

I have two items in an HStack.我在 HStack 中有两个项目。 I want one of them to be perfectly horizontally centered and the other to be on the left side (have an alignment of.leading).我希望其中一个完全水平居中,另一个位于左侧(有一个 alignment of.leading)。 Here is my code so far:到目前为止,这是我的代码:

HStack {
            Text("1")
                .frame(alignment: .leading)
            
            Text("Hello")
                .frame(alignment: .center)
        }

I have figured out that the.overlay method works.我发现 .overlay 方法有效。 However, I still want Text("Hello") to be aware of the position of Text("1") so that if Text("Hello") were a longer string, it would know not to cover up Text("1"), which is exactly what happens when the.overlay function is used.但是,我仍然希望 Text("Hello") 知道 Text("1") 的 position,这样如果 Text("Hello") 是一个更长的字符串,它就会知道不要掩盖 Text("1" ),这正是使用 the.overlay function 时发生的情况。 So I'm wondering if there are any other solutions.所以我想知道是否还有其他解决方案。

You can add one more Text view inside HStack as hidden which have the same content as your left align text view along with Spacer .您可以在HStack中添加一个隐藏的Text视图,其内容与左对齐文本视图以及Spacer相同。 Something like this.像这样的东西。

HStack {
    Text("1")
    Spacer()
    Text("Good Morning, Hello World. This is long message")
        .multilineTextAlignment(.center)
    Spacer()
    Text("1") // Set the same content as left aligned text view
        .hidden()
 }
 .padding(.horizontal)

Preview预习

Not sure if it's the best way, but you can use a GeometryReader to get the screen width and skip the first half.不确定这是否是最好的方法,但您可以使用GeometryReader获取屏幕宽度并跳过前半部分。 To place the text exactly in the center, you should also calculate the width of the text.要将文本恰好放在中心,您还应该计算文本的宽度。 you can use a simple extension to get the size of your text:您可以使用一个简单的扩展来获取文本的大小:

extension String {
public func size(withFont font: UIFont) -> CGSize {
    (self as NSString).size(withAttributes: [.font: font])
}

} }

Here is the example code:这是示例代码:

GeometryReader { geo in
            
            HStack {
                Spacer()
                    .frame(width: (geo.size.width - "center".size(withFont: UIFont.systemFont(ofSize: 18)).width) / 2)
                HStack {
                    Text("center")
                    Text("another")
                }
            }
            
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM