SwiftUI ScrollView 没有更新?

you*_*jin 17 swiftui

目标

获取数据以显示在 scrollView

预期结果

滚动视图中显示的数据

实际结果

空白视图

选择

use List,但不灵活(不能去掉分隔符,不能有多个列)

代码

struct Object: Identifiable {
    var id: String
}

struct Test: View {
    @State var array = [Object]()

    var body: some View {
//        return VStack { // uncomment this to see that it works perfectly fine
        return ScrollView(.vertical) {
            ForEach(array) { o in
                Text(o.id)
            }
        }
        .onAppear(perform: {
            self.array = [Object(id: "1"),Object(id: "2"),Object(id: "3"),Object(id: "4"),Object(id: "5")]
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*ina 21

解决这个问题的一个不太笨的方法是将 ScrollView 包含在一个 IF 语句中,该语句检查数组是否为空

if !self.array.isEmpty{
     ScrollView(.vertical) {
          ForEach(array) { o in
               Text(o.id)
          }
     }
}
Run Code Online (Sandbox Code Playgroud)


sfu*_*ng3 1

预期的行为发生在Xcode 11.1但没有发生Xcode 11.2.1

我添加了一个frame修饰符,使ScrollViewScrollView出现

struct Object: Identifiable {
    var id: String
}

struct ContentView: View {
    @State var array = [Object]()

    var body: some View {
        ScrollView(.vertical) {
            ForEach(array) { o in
                Text(o.id)
            }
        }
        .frame(height: 40)
        .onAppear(perform: {
            self.array = [Object(id: "1"),Object(id: "2"),Object(id: "3"),Object(id: "4"),Object(id: "5")]
        })
    }
}
Run Code Online (Sandbox Code Playgroud)