Home > OS >  SwiftUI - weird spacing in HStack with two Texts
SwiftUI - weird spacing in HStack with two Texts

Time:08-02

I am creating a "News" SwiftUI widget and I need to display rows, each containing time and news header.

I am using a VStack containing HStack's for each item but I am encountering an issue with extra HStack spacing between the two Text's. I need the left Text taking all the width needed for its content and the right Text taking all the width that is left. Seems to work as expected for the longer date (second line) for not for the first one.

In AutoLayout world I would need to play around with Content hugging / Compression resistance priority to achieve what I need but not sure what to do in SwiftUI.

Here's my code for creating the view:

  private func createView(from headers: [NewsHeaderEntry.NewsHeader], with first: Int) -> some View {
        GeometryReader { metrics in
            VStack(alignment: .leading, spacing: 16) {
                title
                ForEach(headers[0...first - 1]) { header in
                    HStack(spacing: 4) {
                            Text(header.newsAt)
                                .font(.system(size: 12))
                                .fontWeight(.light)
                                .background(.green)
                                .frame(alignment: .leading)
                            Text(header.title)
                                .font(.system(size: 14))
                                .fontWeight(.semibold)
                                .redacted(reason: header.isPlaceholder ? .placeholder : .init())
                                .background(.yellow)
                                .lineLimit(2)
                                .frame(maxWidth: .infinity, alignment: .trailing)
                        }
                        .background(.red)
                        .frame(maxWidth: .infinity, alignment: .center)
                    .padding(.horizontal, 8)
                }
                Spacer()
            }
            .frame(width: metrics.size.width)
            .background(.blue)
        }
    }

I have also tried setting maxWidth: .infinity for the left Text as well but it resulted in equal widths for both Texts which is not what I need.

Result:

Update: Without .padding(.horizontal, 8) the spacing works as expected but I need the horizontal spacing from the design perspective.

[Result without padding:Simulator

  • Related