简体   繁体   中英

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: 在此处输入图片说明 instead of this: 在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM