SwiftUI:在动态列表顶部添加视图会导致视图缩小 [英] SwiftUI: adding a View at the top of a dynamic List causes the View to shrink
问题描述
我有一个简单的 SwiftUI
列表,当我在列表顶部添加 View
时,它会从 Combine
发布者异步显示数字.用作标题视图,我遇到了奇怪的 shrink 或 flicker ,当数据重新绘制 Content View
时,标题出现了发布者的退货:
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 ?
推荐答案
解决方法是使用显式列表行inset,如下所示...
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屋!