我正在制作笔记应用并添加滑动以删除行方法。我遇到的问题是当表格视图中保存了多个笔记时,我会滑动一行删除它会删除所有笔记。此外,当我退出应用程序并返回时,笔记又回到了表格视图中。这是我的代码:
class MasterViewController: UITableViewController {
var notesItems: NSMutableArray = NSMutableArray()
override func viewDidAppear(animated: Bool) {
let userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()
let itemListFromUserDefaults:NSMutableArray? = userDefaults.objectForKey("itemList") as? NSMutableArray
if ((itemListFromUserDefaults) != nil) {
notesItems = itemListFromUserDefaults!
}
self.tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(false, animated: true)
self.navigationController?.toolbarHidden = false
self.tableView.dataSource = self
UINavigationBar.appearance().barTintColor = UIColor.orangeColor()
UIToolbar.appearance().barTintColor = UIColor.orangeColor()
}
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return notesItems.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let notesItem:NSDictionary = notesItems.objectAtIndex(indexPath.row) as! NSDictionary
cell.textLabel?.text = notesItem.objectForKey("text") as? String
return cell
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
self.tableView.reloadData()
self.tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
// Delete the row from the data source
}
}
}
答案 0 :(得分:2)
commitEditingStyle
中的代码完全错误。
deleteRowsAtIndexPaths
。beginUpdates/endUpdated
拨打deleteRowsAtIndexPaths
一个电话。你想:
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
// remove an object from notesItem for this index path
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
}