Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI LazyGrid dynamic column width

Tags:

swiftui

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

like image 332
MattBlack Avatar asked Jun 24 '20 15:06

MattBlack


1 Answers

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

like image 93
Asperi Avatar answered Oct 31 '22 17:10

Asperi