SwiftUI:在动态列表的顶部添加一个视图会导致视图缩小 [英] SwiftUI: adding a View at the top of a dynamic List causes the View to shrink

查看:20
本文介绍了SwiftUI:在动态列表的顶部添加一个视图会导致视图缩小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 SwiftUI 列表,当我在列表顶部添加一个 View 时,它会异步显示来自 Combine 发布者的数字作为标题视图,当数据重新绘制 Content View 时,标题会出现奇怪的 shrinkflicker从发布者返回:

I have a simple SwiftUI list that displays numbers asynchronously from a Combine publisher, when I add a View at the top of the list to act as a header view, I face a weird shrink or flicker happens for the header at the time the Content View gets redrawn when the data returns from the publisher:

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

here's the view-model class that has the publisher:

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 结构:

and here's the ContentView struct that interacts with the above view model:

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 中,但没有任何改变.

I've tried to separate the VStack at the top of the list into an external View but nothing changed.

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

what's causing this weird shrink and is there a way to avoid it ?

推荐答案

修复是使用显式列表行插入,如下所示...

The fix is to use explicit list rows inset, something like as below...

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:在动态列表的顶部添加一个视图会导致视图缩小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆