ios - 如何在 HStack 中始终位于中心的 Spacers 之间创建 View ?

标签 ios swift swiftui

我想达到什么。无论两侧的文本宽度如何,按钮都应始终位于 HStack 的中心.
enter image description here

HStack {
    Text("Foooooooo")
    Spacer(minLength: 5)
    Button(action: { }) {
        Text("Bar")
    }
    Spacer()
    Text("Baz")
}
.font(.system(size: 16, weight: .heavy, design: .rounded))
.padding()
enter image description here
我也尝试使用 GeometryReader并为每个 Text 设置帧大小和 Button然而,在 View 中存在两个问题,
  • GeometryReader 返回的 View 将占据父级提供给它的整个 View ,而不是实际的内在内容大小,该空间仅够 Text 使用。 , SpacerButton
  • 第一个 Text 内的字符串不能左对齐,最后一个 Text 中的字符串也是如此。无法右对齐
  • 最佳答案

    这是您的情况的可能方法。使用 Xcode 12/iOS 14 准备和测试的演示
    demo

        HStack {
            Spacer()
                .overlay(Text("Foooooooo"), alignment: .leading)
    
            Button(action: { }) {
                Text("Bar")
            }
    
            Spacer()
                .overlay(Text("Baz"), alignment: .trailing)
        }
        .font(.system(size: 16, weight: .heavy, design: .rounded))
        .padding()
    
    backup

    关于ios - 如何在 HStack 中始终位于中心的 Spacers 之间创建 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63755532/

    相关文章:

    ios - 无法在简单的 Times Table 应用程序中显示 TableView 数据

    ios - Swift 4 - swift 中带有两个圆角的 ImageView ?

    xcode - 使用未解析的标识符 'PresentationButton'

    swiftui - 如何在SwiftUI中随时从 subview 作为父 View 访问数据?

    html - iPad 的简单 HTML 布局

    ios - 我需要随机的几何形状、 Material 或其他东西吗? - 场景套件, swift

    string - 在 Swift 中,NSAttributedString 的字符数比 String 多吗?

    arrays - 为标签数组中的文本分配不重复的随机数 Swift

    ios - 添加了文本编辑器/SwiftUi

    iphone - 在 didReceiveMemoryWarning 之后我应该用什么方法重新创建资源?