SwiftUI:在动态列表顶部添加视图会导致视图缩小

时间:2020-02-07 08:50:08

标签: ios swift swiftui

我有一个简单的SwiftUI列表,它从Combine发布者异步显示数字,当我在列表顶部添加View作为标题视图时,我面对数据从发布者返回时,Content View重绘时,标题出现奇怪的收缩闪烁

这是具有发布者的视图模型类:

class ViewModel: ObservableObject {
    @Published var items: [Int] = []
    var subscriptions = Set<AnyCancellable>()

    init() {
            (0...10)
            .publisher
            .delay(for: .seconds(3), scheduler: DispatchQueue.main) //to simulate async call
            .sink { (value) in
            self.items.append(value)
        }
        .store(in: &subscriptions)
    }
}

这是与上述视图模型交互的ContentView结构:

struct ContentView: View {
    @ObservedObject var viewModel: ViewModel
    var body: some View {

        List {
            VStack {
                Rectangle()
                Text("Some Text")
                Text("Some Other Very Long Text Some Other Some Other Long Text")
            }
            .background(Color.red)

            ForEach(viewModel.items, id: \.self) {  item in
                Text("\(item)")
            }
        }
    }
}

结果如下:

enter image description here

我尝试将列表顶部的VStack分离为外部View,但没有任何改变。

是什么原因导致这种奇怪的收缩,有什么办法可以避免?

1 个答案:

答案 0 :(得分:4)

解决方法是使用显式列表行插入,如下所示...

List {
    VStack {
        Rectangle()
        Text("Some Text")
        Text("Some Other Very Long Text Some Other Some Other Long Text")
    }
    .background(Color.red)
    .listRowInsets(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10)

    ForEach(viewModel.items, id: \.self) {  item in
        Text("\(item)")
    }
    .listRowInsets(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10)
}