首页 > 解决方案 > SwiftUI layout with left and center views, that avoid overlap

问题描述

Imagine something like a navigation bar — there is an item on the left and in the center. I can create this layout with SwiftUI. (A ZStack is one way.)

But if the text is too long, I want to avoid overlap by shifting the center item over. I can do this with autolayout by constraining the center item to the center of its parent with one priority, and then constraining them not to overlap with a higher priority.

I keep wishing I had something like constraints in SwiftUI.

Any way to do this layout in SwiftUI?

enter image description here

标签: swiftui

解决方案


您可以通过结合使用嵌入HStacksfixedSized()、 和layoutPriority()操作来做到这一点。

尝试居中,但在需要时移动

源代码

struct CentreTheDarnTextView: View {
    var titleText: String
    var body: some View {
        HStack {
            HStack {
                Text("I am Left Text")
                    .fixedSize()
                Spacer()
            }
            Text(titleText)
                .layoutPriority(1)
                .minimumScaleFactor(0.5)
                .lineLimit(1)
                .foregroundColor(.red)
            HStack {
                Spacer()
                Text("")
            }
        }.padding(.all, 8)
    }
}

struct CentreTheDarnTextView_Previews: PreviewProvider {
    static var previews: some View {
        CentreTheDarnTextView(titleText: "I am Centre Text")
            .previewLayout(.fixed(width:400, height:44))
        CentreTheDarnTextView(titleText: "I am much longer Centre Text")
            .previewLayout(.fixed(width:400, height:44))
        CentreTheDarnTextView(titleText: "I am rediculously long Centre Text that makes programmers cry")
            .previewLayout(.fixed(width:400, height:44))
    }
}
  • .fixedSize()强制文本不被剪裁,并布局全尺寸。
  • .layoutPriority(1)非常相似,但您仍然可以应用.minimumScaleFactor(),.lineLimit()来处理空间不足的问题。
  • 那个空Text("")就是秘方。

推荐阅读