【问题标题】:ForEach in ScrollView not updating until interactionScrollView 中的 ForEach 直到交互才更新
【发布时间】:2021-02-16 19:49:58
【问题描述】:

向数组添加或从数组中删除时,除非用户与ScrollView 交互,否则视图不会更新。

Model 是一个ObservableObject,在应用生命周期的早期被声明为StateObject,然后作为EnvironmentObject 传递。

数据只是一个带有对象数组的自定义Profile对象,当添加到store.profile!.tasks.append()或从视图中删除时,除非用户滚动ScrollView,否则不会更新;我的意思是字面意思是 1 个像素。

我尝试过的

  • 将 ForEach 包装在 LazyVStack 或 VStack 中
  • 将 NavigationLink 包装在 VStack 中
  • 确保尺寸为全高,以防需要重新计算

代码

class Profile: Identifiable, Codable, Equatable
    var tasks: [Task]
}


struct Task: Identifiable, Codable, Equatable {
    var createdBy: String
    var title: String
    var date: Date
}

class Store : ObservableObject {
    @Published var profile: Profile?
}

struct ListView: View {

@EnvironmentObject var store: Store

  var body: some View {
     GeometryReader { geometry in
        ZStack(alignment: .bottomTrailing) {
          ScrollView(.vertical, showsIndicators: false){
              ForEach(store.profile!.tasks.filter({ return $0.createdBy == store.profile!.uid}).indices, id: \.self) { index in
                 NavigationLink(destination: DetailView().environmentObject(store)) {
                      TasksRow().id(UUID()) 
                 }
             }
          }
           .frame(maxWidth: geometry.size.width, alignment: .center)
           .frame(maxHeight: geometry.size.height)
           .background(Color.gray)
       }
    }
 }

【问题讨论】:

    标签: swiftui combine


    【解决方案1】:

    您的Profile 是引用类型,因此当您在其中附加任务时,对配置文件的引用不会更改,因此已发布不起作用。

    对配置文件使用值类型(即struct

    struct Profile: Identifiable, Codable, Equatable
        var tasks: [Task]
    }
    

    现在将任务附加到配置文件将更改配置文件本身,发布者发送事件和视图将刷新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-28
      • 2016-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      • 2017-11-10
      • 1970-01-01
      相关资源
      最近更新 更多