如何在SwiftUI中显示来自UITableView之类的数据源的视图列表 [英] How to show list of views from a dataSource like UITableView in SwiftUI
问题描述
在SwiftUI中,我们有List
表示可重复使用的项目.就像UIKit
中的UITableView
.
In SwiftUI, we have List
to represent reusable items. Just like UITableView
in UIKit
.
静态列表的构建方式如下:
Static lists builds like this:
List {
Text("cell")
Text("cell")
Text("cell")
Text("cell")
}
但是似乎完全不可重用
如何拥有一个包含一些对象的数组,并根据该数组及其动态大小(计数)填充列表?
How can I have an array of some objects and fill the list based on the array and its dynamic size (count)?
推荐答案
通常是根据动态数据生成的动态视图.因此,您应该考虑将数据结构用于重复视图,然后根据如下数据构建列表:
Dynamic views usually generated from dynamic data. So you should consider using a data structure for your repeating views, then build the list based on data like this:
struct Student: Identifiable {
let name: String
let id: Int
}
struct ContentView : View {
// Could be `@State Var` instead
let students = [
Student(name: "AAAAA", id: 1),
Student(name: "BBBBB", id: 2),
Student(name: "CCCCC", id: 3), // Notice that trailing comma is not problem here?
]
var body: some View {
List(students) { student in
Text(student.name)
}
}
}
数组应包含Identifiable
个对象(推荐)
Array should contain Identifiable
objects (Recommended)
,或者如果您不想遵守Identifiable
协议,则可以这样使用它:
or if you not prefer to conform to Identifiable
protocol you can use it like this:
struct Book {
let anyPropertyName: String
let title: String
}
struct ContentView : View {
// Could be `@State Var` instead
let books = [
Book(anyPropertyName: "AAAA", title: "1111"),
Book(anyPropertyName: "BBBB", title: "2222"),
Book(anyPropertyName: "CCCC", title: "3333")
]
var body: some View {
List(books.identified(by: \.anyPropertyName)) { book in
Text(book.title)
}
}
}
请注意,数据源可以是@State var
,并且可以在任何@State var
发生更改时更新UI.
Note that dataSource can be @State var
and it gives the ability to update the UI whenever any @State var
changes.
最后,虽然看起来好像没有在重复使用,但实际上是!限制为10个静态项目与重复使用无关.
Lastly, although it seems like it's not reusing, but actually it is! The limit of 10 static items has nothing to do with reusing.
这篇关于如何在SwiftUI中显示来自UITableView之类的数据源的视图列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!