我有一个带有列表的水平 ScrollView 。水平滚动时,如何使列表对齐到边缘。
struct RowView: View {
var post: Post
var body: some View {
GeometryReader { geometry in
VStack {
Text(self.post.title)
Text(self.post.description)
}.frame(width: geometry.size.width, height: 200)
//.border(Color(#colorLiteral(red: 0.1764705926, green: 0.01176470611, blue: 0.5607843399, alpha: 1)))
.background(Color(#colorLiteral(red: 0.721568644, green: 0.8862745166, blue: 0.5921568871, alpha: 1)))
.cornerRadius(10, antialiased: true)
.padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
}
}
}
struct ListView: View {
var n: Int
@State var posts = [Post(id: UUID(), title: "1", description: "11"),
Post(id: UUID(), title: "2", description: "22"),
Post(id: UUID(), title: "3", description: "33")]
var body: some View {
GeometryReader { geometry in
ScrollView {
ForEach(0..<self.n) { n in
RowView(post: self.posts[0])
//.border(Color(#colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1)))
.frame(width: geometry.size.width, height: 200)
}
}
}
}
}
struct ContentView: View {
init() {
initGlobalStyles()
}
func initGlobalStyles() {
UITableView.appearance().separatorColor = .clear
}
var body: some View {
GeometryReader { geometry in
NavigationView {
ScrollView(.horizontal) {
HStack {
ForEach(0..<3) { _ in
ListView(n: 1000) // crashes
.frame(width: geometry.size.width - 60)
}
}.padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 0))
}
}
}
}
}
当我给 ListView(n: 1000)
赋值时, View 崩溃了。应用程序启动并显示一段时间的白屏,然后出现黑屏。
2019-10-06 15:52:57.644766+0530 MyApp[12366:732544] [Render] CoreAnimation: Message::send_message() returned 0x1000000e
如何解决这个问题?我的假设是它会使用像 UITableView
这样的出列单元格之类的东西,但不确定它为什么会崩溃。
最佳答案
所提供的代码存在一些问题。最重要的是你没有使用 List
只是一个嵌套在 ScrollView
中的 ForEach
,这相当于在 UIStack 中放置 1000 个 UIView - 效率不高。还有很多硬编码维度,其中相当一部分是重复的,但在计算 View 时仍然会增加很大的负担。
我已经简化了很多并且它在 n = 10000 下运行而不会崩溃:
struct ContentView: View {
var body: some View {
GeometryReader { geometry in
NavigationView {
ScrollView(.horizontal) {
HStack {
ForEach(0..<3) { _ in
ListView(n: 10000)
.frame(width: geometry.size.width - 60)
}
} .padding([.leading], 10)
}
}
}
}
}
struct ListView: View {
var n: Int
@State var posts = [Post(id: UUID(), title: "1", description: "11"),
Post(id: UUID(), title: "2", description: "22"),
Post(id: UUID(), title: "3", description: "33")]
var body: some View {
List(0..<self.n) { n in
RowView(post: self.posts[0])
.frame(height: 200)
}
}
}
struct RowView: View {
var post: Post
var body: some View {
HStack {
Spacer()
VStack {
Spacer()
Text(self.post.title)
Text(self.post.description)
Spacer()
}
Spacer()
} .background(RoundedRectangle(cornerRadius: 10)
.fill(Color(#colorLiteral(red: 0.721568644, green: 0.8862745166, blue: 0.5921568871, alpha: 1))))
}
}
关于ios - 在 SwiftUI 中创建包含 1000 个元素的列表时出现性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58256373/