完成个人目标后更新并重新加载 UITableView

Update and reload UITableView after completion of personal goals

我正在构建某种待办事项列表应用程序。易于使用的工具可帮助建立积极的例程、习惯、设定个人目标、跟踪您的进度。但是当我创建一个用户设置个人目标时,he/she 必须向左滑动,这是一个数字加起来就是用户的进度。我设法创造了它。但是当用户完成目标时,它会说完成目标,这很好,但我希望 Tableview Cell 更新并删除完成视图!

问题是它不从 uitableview 更新数据。请帮助我,非常感谢您抽出时间。

//GCell.swift

func configureCell(goal: Goal) {
    self.goalDescriptionLbl.text = goal.goalDescription
    self.goalDescriptionLbl2.text = goal.goalDescription2
    
    self.goalProgressLbl.text = String(describing: goal.goalProgress)
    
    if goal.goalProgress == goal.goalCompletion {
        self.completionView.isHidden = false
    } else {
        self.completionView.isHidden = true

    }

    //GVC.swift

    func setProgress(atIndexPath indexPath: IndexPath) {
    guard let managedContext = appDelegate?.persistentContainer.viewContext else { return }
    
    let chosenGoal = goals[indexPath.row]
    
    if chosenGoal.goalProgress < chosenGoal.goalCompletion {
        chosenGoal.goalProgress = chosenGoal.goalProgress + 1
    } else {
        return
    }
    
    do {
        try managedContext.save()
        print("Successfully set progress")
    } catch {
        debugPrint("Could not set progress: \(error.localizedDescription)")
    }
}

    func removeGoal(atIndexPath indexPath: IndexPath) {
    guard let managedContext = appDelegate?.persistentContainer.viewContext else { return }
    managedContext.delete(goals[indexPath.row])
    
    do {
        try managedContext.save()
        print("Successfully removed goal!")
    } catch {
        debugPrint("Could not remove: \(error.localizedDescription)")
    }
}

    func tableView(_ tableView: UITableView,
               leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
{
    let addAction = UIContextualAction(style: .normal, title:  "", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
        self.setProgress(atIndexPath: indexPath)
        tableView.reloadRows(at: [indexPath], with: .automatic)
        success(true)
    })
    addAction.image = UIImage(named: "Add1")
    self.fetchCoreDataObjects()
    
    addAction.backgroundColor = #colorLiteral(red: 0.9529411765, green: 0.9607843137, blue: 0.9803921569, alpha: 1)
    return UISwipeActionsConfiguration(actions: [addAction])
} }

// cellForRowAt indexPath

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "goalCell") as? GoalCell else {
        return UITableViewCell() }
    
    let goal = goals[indexPath.row]
    
    // pass class(Object) from GoalCell.swift file
    // Core Data NS fetch - 4
    cell.configureCell(goal: goal)
    
    // Did select 2
    cell.goalDescriptionLbl2?.text = ""
    
    return cell
}
    //managedContext 
    func fetch(completion: (_ complete: Bool) -> ()) {
    guard let managedContext = appDelegate?.persistentContainer.viewContext else { return }
    
    let fetchRequest = NSFetchRequest<Goal>(entityName: "Goal")
    
    do {
        goals = try managedContext.fetch(fetchRequest)
        print("Successfully fetched data.")
        completion(true)
    } catch {
        debugPrint("Could not fetch: \(error.localizedDescription)")
        completion(true)
    }
}

首先,按照上面显示的img更改您的模型。

其次,将``GoalsVC```中的setProgress函数代码更改为:

    func setProgress(atIndexPath indexPath : IndexPath) {
        guard let managedContext = appDelegate?.persistentContainer.viewContext else { return }
        let selectedGoal = goals[indexPath.row]
        if selectedGoal.goalProgressValue < selectedGoal.goalCompletionValue - 1 {
            selectedGoal.goalProgressValue = selectedGoal.goalProgressValue + 1
        } else {
            // By the time the code executing, goal is met.
            selectedGoal.goalProgressValue = selectedGoal.goalProgressValue + 1
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                // the code in the block is all about hiding the completion view
                selectedGoal.goalCompleteViewShowed = true
                do {
                    try managedContext.save()
                    self.tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
                } catch {
                    debugPrint("Couldn't set progress. \(error.localizedDescription)")
                }
            }
            return
        }
        
        do {
            try managedContext.save()
        } catch {
            debugPrint("Couldn't set progress. \(error.localizedDescription)")
        }
    }

第三,将 GoalCell 中的 configureCell 函数更改为:

    func configureCell(goal : Goal) {
        self.goalDescriptionLabel.text = goal.goalDescription
        self.goalTermLabel.text = goal.goalType
        self.goalProgressLabel.text = "\(goal.goalProgressValue)"
        self.goalIndex = goal.index
        
        if lastIndex == nil {
            lastIndex = 0
        } else {
            lastIndex = goalIndex
        }
        
        // I think you might just want the completionView to show again since it is just for the notification purpose.
        if goal.goalProgressValue == goal.goalCompletionValue && !goal.goalCompleteViewShowed { 
            self.goalCompleteView.isHidden = false
        } else {
            self.goalCompleteView.isHidden = true
        }
    }

代码刚刚用您在 github 中上传的项目进行了测试。