ios - 滑动单元格以从 Core Data 更改当前单元格内的值
问题描述
我在 tableView 中有一个单元格,我想在每次滑动时反复滑动它以更改其中的值。我有一个核心数据,用于存储来自另一个 ViewController 的数据。
class HomeViewController: UITableViewController {
//MARK:- Properties
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
// All Pills array
var pillsArray: [Pill] = []
var pillsRemaining: Int = 0
override func viewWillAppear(_ animated: Bool) {
//reload table rows
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
// Set the interface color of User
overrideUserInterfaceStyle = .light
// Find user directory path for Core Data
let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
print(dataFilePath)
// Load pillsArray
loadPills()
// Add title to Nav Controller
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
//titleLabel.textColor = UIColor.lightGray
titleLabel.text = "Add Pills"
titleLabel.textAlignment = .center
titleLabel.font = UIFont(name: "Baskerville-Bold", size: 30)
navigationItem.titleView = titleLabel
// Register Cell
self.registerCell()
}
//MARK:- TableView Datasource Methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Add Label if the table View is Empty
if pillsArray.count == 0 {
let homeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height))
homeLabel.text = "Tap '+' to add Pill"
homeLabel.textAlignment = NSTextAlignment.center
tableView.backgroundView = homeLabel
tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
return 0
} else {
tableView.backgroundView = nil
return pillsArray.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Create Cell
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ReminderCell", for: indexPath) as? PillTableViewCell else {
fatalError("Could not register cell with identifier ReminderCell")
}
let singlePill = pillsArray[indexPath.row]
cell.pillNameCell.text = singlePill.pillName
cell.instructionsCell.text = singlePill.pillInstruction
cell.pillTimerCell.text = singlePill.pillStartTimer
if let pillCountLabelText = singlePill.pillsCount {
if let selectedPillTypeText = singlePill.selectedPillType {
singlePill.pillsRemaining = pillCountLabelText
cell.pillsLeft.text = pillCountLabelText
// if Int(pillCountLabelText) == pillsRemaining {
// cell.pillsLeft.text = "pills left \(pillCountLabelText) \. (selectedPillTypeText)"
// } else {
// cell.pillsLeft.text = "pills left \(pillsRemaining) \(selectedPillTypeText)"
// }
}
}
// cell.pillImageView.backgroundColor = singlePill.pillColor
// Add color to pill taken img (ternary operation)
cell.doneImageView.backgroundColor = singlePill.pillTaken ? .green : .red
return cell
}
//MARK:- TableView Delegate Methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Delete pill from context and tableView
// context.delete(pillsArray[indexPath.row])
// pillsArray.remove(at: indexPath.row)
// Toggle pill taken when selected
// pillsArray[indexPath.row].pillTaken = !pillsArray[indexPath.row].pillTaken
savePillsTaken()
tableView.deselectRow(at: indexPath, animated: true)
}
// Left Swipe Actions (Take and Edit)
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
// Write action code for Take a Pill
let pillTakenAction = UIContextualAction(style: .normal, title: "Done") { (UIContextualAction, UIView, boolValue) in
// Toggle pill taken when selected
self.pillsArray[indexPath.row].pillTaken = !self.pillsArray[indexPath.row].pillTaken
if let pillCountInt = Int(self.pillsArray[indexPath.row].pillsCount ?? "0") {
if let selectedDosageInt = Int(self.pillsArray[indexPath.row].selectedDosage ?? "0") {
self.pillsRemaining = pillCountInt - selectedDosageInt
self.pillsArray[indexPath.row].pillsRemaining = String(self.pillsRemaining)
print(pillCountInt)
print(selectedDosageInt)
}
}
self.savePillsTaken()
boolValue(true)
print(self.pillsRemaining)
}
pillTakenAction.backgroundColor = .green
let editPillAction = UIContextualAction(style: .normal, title: "Edit") { (UIContextualAction, UIView, boolValue) in
print("Edit pill")
boolValue(true)
}
editPillAction.backgroundColor = .gray
let actionSwipes = UISwipeActionsConfiguration(actions: [pillTakenAction, editPillAction])
return actionSwipes
}
// Right Swipe Action
override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
// Write action code for deleting a Pill
let trashAction = UIContextualAction(style: .normal, title: "Delete") { (UIContextualAction, UIView, boolValue) in
// Delete Pill from context and tableView
self.context.delete(self.pillsArray[indexPath.row])
self.pillsArray.remove(at: indexPath.row)
self.savePillsTaken()
boolValue(true)
}
trashAction.backgroundColor = .red
let actionSwipes = UISwipeActionsConfiguration(actions: [trashAction])
return actionSwipes
}
//MARK:- PillCell own methods
func registerCell() {
let pillCell = UINib(nibName: "PillTableViewCell", bundle: nil)
self.tableView.register(pillCell, forCellReuseIdentifier: "ReminderCell")
}
//MARK:- Actions and Segue Methods
@IBAction func saveButtonPressed(segue: UIStoryboardSegue) {
}
func savePillsTaken() {
do {
try context.save()
} catch {
print("Error saving pillsTaken in context, \(error)")
}
tableView.reloadData()
}
func loadPills() {
let request : NSFetchRequest<Pill> = Pill.fetchRequest()
do {
pillsArray = try context.fetch(request)
} catch {
print("Error fetching data from context \(error)")
}
}
}
我想在每次服用药丸剂量时向右滑动以更改药丸数量,它应该显示正确的药丸数量。
解决方案
推荐阅读
- python - 对 pyspark 中的列进行重新分区如何影响分区数?
- c# - c#如何编写可以在类的实例上调用的类方法
- python - 如何将初始数据放在 CreateView 中的表单上?
- python-3.x - Tensorflow 对象检测 API - 推理后如何读取 TFRecord?
- python - 输入到 CNN 的超像素
- c - 输入字符串由空终止字符组成
- slack - Slack conversations.list 方法没有列出所有频道
- firebase - 使用数据库时看不到 Firebase 的网络调用?
- java - 在 Java 中引用对象
- android - Kotlin CountDownTimer lateinit 属性尚未初始化且未找到 CoreComponentFactory