swiftforeachswiftuihstackswiftui-layout

SwiftUI truncate content of ForEach


In the following code snippet, the red circles obviously don't fit onto the screen and therefore only the trailing part of the HStack is shown. Instead of that behavior, I want the leading text of the HStack to always be visible and truncate the trailing red circles that don't fit into the available space (replaced with ...). How can I do this?

struct ContentView: View {

    var body: some View {
        HStack {
            Text("This text should always be visible")
                .layoutPriority(1)
            Spacer()
            ForEach(0..<20) { index in
                Image(systemName: "circle.fill")
                    .font(.body)
                    .foregroundColor(.red)
            }
        }
    }
}

So I want this: enter image description here instead of this: enter image description here


Solution

  • Can get everything except the ellipses with:

    struct ContentView: View {
      var body: some View {
        HStack {
          Text("This text should always be visible")
            .fixedSize()
          ForEach(0..<20) { index in
            Image(systemName: "circle.fill")
              .font(.body)
              .foregroundColor(.red)
          }
        }
        .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
      }
    }
    

    In order to get the ellipses you'll probably have to calculate frame sizes or try to get your images into an attributed string which could get pretty complicated. You might also consider a scroll view or grid.