Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List hides when adding in ScrollView SwiftUI

I have added a List inside the ScorllView but it's not showing in canvas after adding inside to ScrollView

here is my code

struct ContentView: View {
    var body: some View {
        ScrollView {
            VStack {
                Text("My List")
                    .font(.largeTitle)
                    .fontWeight(.bold)

                List(0 ..< 5) { item in
                    Text("Hello World")
                }
            }
        }
    }
}

sw

like image 806
Kishore Suthar Avatar asked Nov 20 '19 16:11

Kishore Suthar


Video Answer


1 Answers

The Issue:

That is because List infer it size from its parent View. So when you embed it inside something like VStack that have dynamic height, it can't infer it size correctly.

Solutions:

You have some options here:

1. Size List to match it's content Automatically (Perfect)

You can use ForEach directly instead of using List, then you have more control over the content size

ForEach(0 ..< 5) { item in
    VStack(alignment: .leading) {
        Text("Hello World").frame(height: 42)
        Divider()
    }.padding(.horizontal, 8)
}

You can change all sizes and spacings according to your needs


2. Size List to match it's content manually (Good but not perfect)

Give it a static frame like the way you do in UIKit by setting the .frame() modifier on the List:

List(0 ..< 5) { item in
    Text("Hello World")
}.frame(height: 224)

You can use GeometryReader to find the exact size of the parent and apply it to the List


3. Just show the List (Not good but it works)

add .scaledToFill() modifier to List

like image 156
Mojtaba Hosseini Avatar answered Sep 18 '22 14:09

Mojtaba Hosseini