Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Lists & OnAppear

I have noticed some odd behavior on OnAppear events for List views. I'd think the OnAppear closure would run whenever a view appears on the screen, but it appears to run all at once when the List is loaded.

For example the following code:

@State var rows: [String] = Array(repeating: "Item", count: 20)

var body: some View {

    List(0..<rows.count, id: \.self) { index in
        Text(verbatim: self.rows[index])
            .onAppear {
                print("BOOOOM")
            }
            .frame(height:400)
    }
}

...I would expect the print command to run a couple times on load, then continue to print as I scrolled down. Instead it prints 20 times at once, then again as I start to scroll down.

Any thoughts?

like image 250
mrbenhill Avatar asked Feb 04 '20 00:02

mrbenhill


People also ask

What is a list in SwiftUI?

When you use SwiftUI's List type, you can display a platform-specific list of views. The elements of the list can be static, like the child views of the stacks you've created so far, or dynamically generated. You can even mix static and dynamically generated views.

How do I create a list in SwiftUI?

Probably the simplest way to build a list is to create a new SwiftUI view and wrap the Hello World text in a List: struct StaticListView: View { var body: some View { List { Text("Hello, world!") } } } To add more items to the list, we can just add another line: List { Text("Hello, world!") Text("Hello, SwiftUI!") }

How do I customize a list in SwiftUI?

To begin, create a SwiftUI Xcode project, and create a struct , namely, Data . Let's get back in our ContentView. swift and populate some values into this struct . Now, inside your view, create a List, and use ForEach to add and see all your data in list form.

How do I search a list in SwiftUI?

SwiftUI displays the search bar under the navigation bar title and above the list that you'll filter. In multi-column view, you can choose in which view to display your search bar.


1 Answers

I think it is behaving as expected.

For me it printed 15 times on a Simulator with iPhone 7 and all 20 times on a Simulator with an iPhone 11.

I made a slight change to the print("BOOOOM \(index)")

There is probably a balance with performance and resources that the List abides by in the background.

Load too little and the user will "Get stuck" if scrolling too fast vs loading too much and slowing the scroll animation.

like image 88
lorem ipsum Avatar answered Sep 21 '22 05:09

lorem ipsum