How to have a dynamic List of Views using SwiftUI

后端 未结 8 2040
被撕碎了的回忆
被撕碎了的回忆 2020-12-05 02:44

I can do a static List like

List {
   View1()
   View2()
}

But how do i make a dynamic list of elements from an array? I tried the followin

8条回答
  •  囚心锁ツ
    2020-12-05 02:46

    Is it possible to return different Views based on needs?

    In short: Sort of

    As it's fully described in swift.org, It is IMPOSSIIBLE to have multiple Types returning as opaque type

    If a function with an opaque return type returns from multiple places, all of the possible return values must have the same type. For a generic function, that return type can use the function’s generic type parameters, but it must still be a single type.

    So how List can do that when statically passed some different views?

    List is not returning different types, it returns EmptyView filled with some content view. The builder is able to build a wrapper around any type of view you pass to it, but when you use more and more views, it's not even going to compile at all! (try to pass more than 10 views for example and see what happens)

    As you can see, List contents are some kind of ListCoreCellHost containing a subset of views that proves it's just a container of what it represents.

    What if I have a lot of data, (like contacts) and want to fill a list for that?

    You can conform to Identifiable or use identified(by:) function as described here.

    What if any contact could have a different view?

    As you call them contact, it means they are same thing! You should consider OOP to make them same and use inheritance advantages. But unlike UIKit, the SwiftUI is based on structs. They can not inherit each other.

    So what is the solution?

    You MUST wrap all kind of views you want to display into the single View type. The documentation for EmptyView is not enough to take advantage of that (for now). BUT!!! luckily, you can use UIKit

    How can I take advantage of UIKit for this

    • Implement View1 and View2 on top of UIKit.
    • Define a ContainerView with of UIKit.
    • Implement the ContainerView the way that takes argument and represent View1 or View2 and size to fit.
    • Conform to UIViewRepresentable and implement it's requirements.
    • Make your SwiftUI List to show a list of ContainerView So now it's a single type that can represent multiple views

提交回复
热议问题