iOS:编辑TableView问题中的项目

时间:2015-11-19 03:34:24

标签: ios swift uitableview

所以我正在尝试为tableview中的行编写删除编辑行为。但是,当我在选择一行后点击删除键时,该行不会从tableView中删除。当我第二次尝试这样做时,我得到一个错误,表示找到了意外的零值。

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {   // Handle the Delete action
        // Obtain the name of the genre of movie to be deleted
        let genre: String = genres[indexPath.section]

        // Obtain the list of movies in the genre as AnyObject
        let movies: AnyObject? = applicationDelegate.dict_Genres_dict2[genre]
        let movArray: [String] = movies?.allKeys as! [String] //The nil value is unwrapped on this line
        // Typecast the AnyObject to Swift array of String objects
        var moviesOfGenre: Array<String> = movArray 

        // Delete the identified movie at row
        moviesOfGenre.removeAtIndex(indexPath.row)

        if moviesOfGenre.count == 0 {
            // If no movie remains in the array after deletion, then we need to also delete the genre
            applicationDelegate.dict_Genres_dict2.removeObjectForKey(genre)

            // Since the dictionary has been changed, obtain the genre names again
            genres = applicationDelegate.dict_Genres_dict2.allKeys as! [String]

            // Sort the genre names within itself in alphabetical order
            genres.sortInPlace { $0 < $1 }
        }
        else {
            // At least one more movie remains in the array; therefore, the genre stays.

            // Update the new list of movie for the genre in the NSMutableDictionary
            applicationDelegate.dict_Genres_dict2.setValue(moviesOfGenre, forKey: genre)
        }

        // Reload the rows and sections of the Table View 
        tableView.reloadData()
    }
}

我已经标记了我收到的nil值。任何正确方向的推动都将是最有帮助的。谢谢!

1 个答案:

答案 0 :(得分:0)

删除数组项后。您还需要从表中删除该项目。当您尝试再次删除该数组项时,它显示为nil,因为该项目不可用,但该表未从视图中删除该项目。所以您需要将其删除从表中也可以......

        genres.removeAtIndex(indexPath.row) // or section , delete according to your app   
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)

为什么要拍摄要删除的项目的部分。您没有删除表格中的流派项目。你只删除了moviesOfGenre。您还需要删除表视图项(流派)。从表中删除类型。

您也可以使用滑动删除功能: -

func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
    return true
}

func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
    if (editingStyle == .Delete) {
   // handle delete (by removing the data from your array and updating the tableview)

    self.tableView.beginUpdates()
    self.genres.removeObjectAtIndex(indexPath.row) // also remove an array object if exists.
    self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Left)
    self.tableView.endUpdates()
}