Home > Software engineering >  SwiftUI Text being truncated unexpectedly
SwiftUI Text being truncated unexpectedly

Time:04-01

I have an HStack with three elements, as such:

HStack(alignment: .firstTextBaseline) {
    Text(title.uppercased())
        .lineLimit(1)
    Rectangle()
        .frame(height: 1)
        .foregroundColor(Color(.tertiaryLabel))
    Text(value)
        .lineLimit(1)
}

The first text element is being truncated in favor of the rectangle, which seems odd to me since the rectangle seems like it should compress as much as needed to accommodate the surrounding text.

Demo

I found that adding .fixedSize() to my Text objects fixes this issue, but is that the best/proper solution?

CodePudding user response:

I assume you look for layoutPriority modifier, like

HStack(alignment: .firstTextBaseline) {
    Text(title.uppercased())
        .lineLimit(1)
        .layoutPriority(1)        // << here !!
    Rectangle()
        .frame(height: 1)
        .foregroundColor(Color(.tertiaryLabel))
    Text(value)
        .lineLimit(1)
}
  • Related