ForEach未使用动态内容SwiftUI正确更新 [英] ForEach not properly updating with dynamic content SwiftUI

查看:79
本文介绍了ForEach未使用动态内容SwiftUI正确更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉将这篇帖子写得这么长,但事后看来,我应该向您展示这个问题的更简单的实例,以便您可以更好地了解问题是什么。我假设ForEach的相同问题是这两个bug的根本原因,但我可能错了。仍然包含第二个实例,以便为您提供上下文,但第一个实例应该是您完全理解问题所需的全部内容。

第一个实例:

这是这个问题的视频:https://imgur.com/a/EIg9TSm。如您所见,有4个时间代码,其中2个是最喜欢的,2个不是最喜欢的(用黄色星号表示)。此外,顶部有表示时间代码数组的文本,仅显示为收藏(F)或不收藏(N)列表。我点击Last Time Code(更改为收藏),然后按切换以取消收藏。当我点击保存时,时间代码数组被更新,但是正如您所看到的,列表中没有显示时间代码。但是,您会看到缩减数组的文本立即更新为FNFF,表明它已正确更新为ObservedObject的收藏夹。

当我单击导航并返回页面时,UI已正确更新,并且有3颗黄色星号。这让我假设问题出在ForEach上,因为文本()显示数组已更新,但ForEach没有。在页面外单击可能会重新加载ForEach,这就是它在退出页面后更新的原因。EditCodeView()处理CoreData中TimeCodeVieModel的保存,通过我自己的测试和ObservedObject按预期更新的事实,我99%确定它工作正常。我非常确定我使用的是ForEach的动态版本(因为TimeCodeViewModel是可识别的),所以我不知道如何在保存后立即更新行为。如有任何帮助,我们将不胜感激。

以下是视图的代码:

struct ListTimeCodeView: View {
    
    @ObservedObject var timeCodeListVM: TimeCodeListViewModel
    @State var presentEditTimeCode: Bool = false
    @State var timeCodeEdit: TimeCodeViewModel?

    init() {
        self.timeCodeListVM = TimeCodeListViewModel()
    }

    var body: some View {
        VStack {
            HStack {
                Text("TimeCodes Reduced by Favorite:")
                Text("(self.timeCodeListVM.timeCodes.reduce(into: "") {$0 += $1.isFavorite ? "F" : "N"})")
            }

            List {
                ForEach(self.timeCodeListVM.timeCodes) { timeCode in
                        
                   TimeCodeDetailsCell(fullName: timeCode.fullName, abbreviation: timeCode.abbreviation, color: timeCode.color, isFavorite: timeCode.isFavorite, presentEditTimeCode: $presentEditTimeCode)
                        .contentShape(Rectangle())
                        .onTapGesture {
                            timeCodeEdit = timeCode
                                
                        }
                        .sheet(item: $timeCodeEdit, onDismiss: didDismiss) { detail in
                            EditCodeView(timeCodeEdit: detail)   
                        }
                }    
            }
        }
    }      
}

以下是视图模型的代码(不应该与问题相关,但包含在其中是为了理解):

class TimeCodeListViewModel: ObservableObject {
    
    @Published var timeCodes = [TimeCodeViewModel]()
    
    init() {
        fetchAllTimeCodes()
    }

    func fetchAllTimeCodes() {
        self.timeCodes = CoreDataManager.shared.getAllTimeCodes().map(TimeCodeViewModel.init)
    } 
}


class TimeCodeViewModel: Identifiable {
    var id: String = ""
    var fullName = ""
    var abbreviation = ""
    var color = ""
    var isFavorite = false
    var tags = ""

    
    init(timeCode: TimeCode) {
        self.id = timeCode.id!.uuidString
        self.fullName = timeCode.fullName!
        self.abbreviation = timeCode.abbreviation!
        self.color = timeCode.color!
        self.isFavorite = timeCode.isFavorite
        self.tags = timeCode.tags!
    }
}

第二个实例:

编辑:我意识到可能很难理解代码在做什么,所以我包含了一个演示问题的gif(不幸的是,我的声誉还不够高,无法让它自动显示)。如您所见,我选择了要更改的单元格,然后按下按钮将时间码分配给它。TimeCodeCellViewModels数组在后台发生变化,但在我按下主页按钮并重新打开应用程序(这会触发ForEach刷新)之前,您实际上看不到这种变化。Gif of issue。如果GIF太快,还有这个视频:https://imgur.com/a/Y5xtLJ3

我试图使用HStacks的VStack显示网格视图,但遇到了一个问题,当传入的数组更改时,我用来显示内容的ForEach没有刷新。我知道数组本身正在更改,因为如果我将其简化为字符串并使用text()显示内容,则一旦进行更改,它就会立即正确更新。但是,ForEach循环只有在我关闭并重新打开应用程序时才会更新,从而强制ForEach重新加载。我知道ForEach有一个专门为动态内容设计的特殊版本,但我非常确定我正在使用这个版本,因为我传入了""id:.self""。以下是主要代码片段:

var hoursTimeCode: [[TimeCodeCellViewModel]] = []

// initialize hoursTimeCode

VStack(spacing: 3) {
   ForEach(self.hoursTimeCode, id: .self) {row in
      HStack(spacing: 3){
         HourTimeCodeCell(date: row[0].date) // cell view for hour
            .frame(minWidth: 50)
         ForEach(row.indices, id: .self) {cell in
            // TimeCodeBlockCell displays minutes normally. If it is selected, and a button is pressed, it is assigned a TimeCode which it will then display
            TimeCodeBlockCell(timeCodeCellVM: row[cell], selectedArray: $selectedTimeCodeCells)
               .frame(maxWidth: .infinity)
               .aspectRatio(1.0, contentMode: .fill)
         }
      }                              
   }                          
}

我非常确定它不会改变任何事情,但是我必须为TimeCodeCellViewModel定义一个自定义散列函数,这可能会改变ForEach的行为(被改变的属性包含在散列函数中)。但是,我在使用不同视图模型的项目的另一部分中注意到了相同的ForEach行为,因此我非常怀疑这就是问题所在。

class TimeCodeCellViewModel:Identifiable, Hashable {
    static func == (lhs: TimeCodeCellViewModel, rhs: TimeCodeCellViewModel) -> Bool {
        if lhs.id == rhs.id {
            return true
        }
        else {
            return false
        }
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
        hasher.combine(isSet)
        hasher.combine(timeCode)
        hasher.combine(date)
    }

    var id: String = ""
    var date = Date()
    var isSet = false
    var timeCode: TimeCode
    
    var frame: CGRect = .zero
    
    init(timeCodeCell: TimeCodeCell) {
        self.id = timeCodeCell.id!.uuidString
        self.date = timeCodeCell.date!
        self.isSet = timeCodeCell.isSet
        self.timeCode = timeCodeCell.toTimeCode!
    }
}

推荐答案

下面是代码正常工作所需的代码片段。

有关原因的一些基本信息,请参阅备注

struct EditCodeView:View{
    @EnvironmentObject var timeCodeListVM: TimeCodeListViewModel
    //This will observe changes to the view model
    @ObservedObject var timeCodeViewModel: TimeCodeViewModel
    var body: some View{
        EditTimeCodeView(timeCode: timeCodeViewModel.timeCode)
            .onDisappear(perform: {
                //*********TO SEE CHANGES WHEN YOU EDIT
                //uncomment this line***********
                //_ = timeCodeListVM.update(timeCodeVM: timeCodeViewModel)
            })
    }
}
struct EditTimeCodeView: View{
    //This will observe changes to the core data entity
    @ObservedObject var timeCode: TimeCode
    var body: some View{
        Form{
            TextField("name", text: $timeCode.fullName.bound)
            TextField("appreviation", text: $timeCode.abbreviation.bound)
            Toggle("favorite", isOn: $timeCode.isFavorite)
        }
    }
}
class TimeCodeListViewModel: ObservableObject {
    //Replacing this whole thing with a @FetchRequest would be way more efficient than these extra view models
    //IF you dont want to use @FetchRequest the only other way to observe the persistent store for changes is with NSFetchedResultsController
    //https://stackoverflow.com/questions/67526427/swift-fetchrequest-custom-sorting-function/67527134#67527134
    //This array will not see changes to the variables of the ObservableObjects
    @Published var timeCodeVMs = [TimeCodeViewModel]()
    private var persistenceManager = TimeCodePersistenceManager()
    init() {
        fetchAllTimeCodes()
    }
    
    func fetchAllTimeCodes() {
        //This method does not observe for new and or deleted timecodes. It is a one time thing
        self.timeCodeVMs = persistenceManager.retrieveObjects(sortDescriptors: nil, predicate: nil).map({
            //Pass the whole object there isnt a point to just passing the variables
            //But the way you had it broke the connection
            TimeCodeViewModel(timeCode: $0)
        })
    }
    
    func addNew() -> TimeCodeViewModel{
        let item = TimeCodeViewModel(timeCode: persistenceManager.addSample())
        timeCodeVMs.append(item)
        //will refresh view because there is a change in count
        return item
    }
    ///Call this to save changes
    func update(timeCodeVM: TimeCodeViewModel) -> Bool{
        let result = persistenceManager.updateObject(object: timeCodeVM.timeCode)
        //You have to call this to see changes at the list level
        objectWillChange.send()
        return result
    }
}

//DO you have special code that you aren't including? If not what is the point of this view model?
class TimeCodeViewModel: Identifiable, ObservableObject {
    //Simplify this
    //This is a CoreData object therefore an ObservableObject it needs an @ObservedObject in a View so changes can be seem
    @Published var timeCode: TimeCode
    init(timeCode: TimeCode) {
        self.timeCode = timeCode
    }
}

这篇关于ForEach未使用动态内容SwiftUI正确更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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