【发布时间】:2021-09-18 00:02:35
【问题描述】:
我正在开发一个与Realm 数据库链接的待办事项列表应用程序,但是当我尝试使用允许用户在单元格上滑动以删除数据的“editingStyle”方法时UI 和 Realm 数据库单元格不滑动,应用程序有 2 个屏幕,此方法在第一个屏幕上工作正常,但在另一个屏幕上不起作用,单元格工作正常,只是不会滑动。
我的代码:
import UIKit
import RealmSwift
class CategoryViewController: UITableViewController {
var categories: Results<Category>?
let realm = try! Realm()
override func viewDidLoad() {
super.viewDidLoad()
loadCategories()
tableView.rowHeight = 60.0
}
//MARK: - Creating the table view cell
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CategoryCell", for: indexPath)
cell.textLabel?.text = categories?[indexPath.row].name ?? "No Categories Added Yet"
return cell
}
//MARK: - This will remove a category from the UI & the Realm database, this is a built in swift method
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
if let deleteAction = categories?[indexPath.row] {
do {
try realm.write({
realm.delete(deleteAction)
})
} catch {
print("Error deleting the cell \(error)")
}
}
}
tableView.deleteRows(at: [indexPath], with: .fade)
}
//MARK: - TableView Delegate Methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "goToItems", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! TodoListViewController
if let indexPath = tableView.indexPathForSelectedRow {
destinationVC.selectedCategory = categories?[indexPath.row]
}
}
//MARK: - Add New Categories
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Add New Category", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Add", style: .default) { (action) in
// What happens when user clicks add button
let newCategory = Category()
newCategory.name = textField.text!
self.saveCategories(category: newCategory)
}
alert.addAction(action)
alert.addTextField { (field) in
textField = field
textField.placeholder = "Add a new category"
}
present(alert, animated: true, completion: nil)
}
//MARK: - Data Manipulation Methods
func saveCategories(category: Category) {
do {
try realm.write({
realm.add(category)
})
} catch {
print("Error saving category \(error)")
}
tableView.reloadData()
}
func loadCategories() {
categories = realm.objects(Category.self)
tableView.reloadData()
}
}
【问题讨论】:
-
不刷卡或给出错误,因为您的代码看起来不错
-
看看实施
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool能否解决您的问题
标签: ios swift uitableview swipe