【问题标题】:SwiftUI: adding a View at the top of a dynamic List causes the View to shrinkSwiftUI:在动态列表顶部添加视图会导致视图缩小
【发布时间】:2020-02-07 16:59:39
【问题描述】:

我有一个简单的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)")
            }
        }
    }
}

结果如下:

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

是什么导致了这种奇怪的收缩,有没有办法避免它?

【问题讨论】:

    标签: ios swift swiftui


    【解决方案1】:

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

    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)
    }
    

    【讨论】:

    • 这是一个很好的解决方法,您回答了问题的第一部分,但为什么会发生这种情况?这在 SwiftUI 中很重要吗?
    • @JAHelia,它看起来像一个错误,但我不确定。您可以向 Apple 发送反馈,他们可以肯定地说出来。
    • 嗯,似乎对我不起作用。我最终改用了 TableViewController。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多