[英]How to get on screen rows from List in SwiftUI?
I'm trying to put a Text
for each visible (within the screen bounds) row in a List of their current index in all the visible rows.我正在尝试将每个可见(在屏幕范围内)行的
Text
放在所有可见行中它们当前索引的列表中。
I have an example here.我这里有一个例子。 If I have a list showing 3 rows at a time, and initially I want it showing like this:
如果我有一个一次显示 3 行的列表,并且最初我希望它显示如下:
___|___
A | 0
B | 1
C | 2
-------
And if I scroll the list down, and A goes out of the screen, then it will be like如果我向下滚动列表,然后 A 走出屏幕,那么它就像
___|___
B | 0
C | 1
D | 2
-------
Any idea how can I do it?知道我该怎么做吗?
Besides, I used to use UITableView.visibleCells to obtain the visible cells on screen, but I couldn't find something similar in SwiftUI.此外,我曾经使用UITableView.visibleCells来获取屏幕上的可见单元格,但我在 SwiftUI 中找不到类似的东西。 How exactly am I suppose to get visible row in a list with only index provided in SwiftUI?
我究竟应该如何在 SwiftUI 中仅提供索引的列表中获得可见行?
Hope someone can direct me to the right place.希望有人可以指导我到正确的地方。 Thanks a lot!
非常感谢!
You can use onAppear and onDisappear functions to maintain a list of visible rows and then use these to find a visible index.您可以使用onAppear和onDisappear函数来维护可见行的列表,然后使用它们来查找可见索引。
struct ContentView: View {
let rows = (Unicode.Scalar("A").value...Unicode.Scalar("Z").value)
.map { String(Unicode.Scalar($0)!) }
@State var visibleRows: Set<String> = []
var body: some View {
List(rows, id: \.self) { row in
HStack {
Text(row)
.padding(40)
.onAppear { self.visibleRows.insert(row) }
.onDisappear { self.visibleRows.remove(row) }
}
Spacer()
Text(self.getVisibleIndex(for: row)?.description ?? "")
}
}
func getVisibleIndex(for row: String) -> Int? {
visibleRows.sorted().firstIndex(of: row)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.