13

How can I make the Grid item width dynamic so that it takes the width of the text?

Using the code below the text is truncated, I would like all the text to be displayed without the truncation, taking into account the variable text lengths.

struct ContentView: View {
    
    let data = ["O Menino","The Boy", "The Girl", "A Menina","Mae","Mother"]
    
    let layout = [
        GridItem(.adaptive(minimum:50))
        
    ]
    
    var body: some View {
       
        ScrollView{
            LazyVGrid(columns: layout, spacing: 20){
                ForEach(data, id: \.self){ item in
                    VStack{
                        Text(item).lineLimit(1)
                    }.background(Color.red)
                }
            }
        }
    }
}

enter image description here

MattBlack
  • 3,616
  • 7
  • 32
  • 58

1 Answers1

6

It is VGrid, it grows vertically filling columns. In your case it is only one column.

If you want to fit all those content in screen, you'd need to increase number of grid columns, like

let data = ["O Menino","The Boy", "The Girl", "A Menina","Mae","Mother"]
let layout = Array(repeating: GridItem(.adaptive(minimum:50)), count: 4)

demo

Asperi
  • 228,894
  • 20
  • 464
  • 690
  • I guess this is what I am trying to acheieve, as you can see the number of columns varies depending on the row content, I have been using a UIRepresentable collection view at the moment but was hoping for a more native swiftUI approach. https://stackoverflow.com/questions/33625895/how-can-i-make-tag-list-in-swift/45734125 – MattBlack Jun 25 '20 at 08:05
  • I assume the following posts might be helpful for you https://stackoverflow.com/a/58876712/12299030 and https://stackoverflow.com/a/62103264/12299030 – Asperi Aug 16 '20 at 15:30