TableView在segue之后显示错误的数据

时间:2016-01-07 13:53:09

标签: ios swift uitableview core-data

这是一个项目是一个简单的汽车字典,我使用的是核心数据,来自服务器上传的.csv文件。

当我在第一个tableview中选择单词触发第二页以读取另一个tableview中的定义时,问题始终显示不正确的单词和定义。

2 个答案:

答案 0 :(得分:1)

您忽略了从tableView.indexPathForSelectedRow获得的索引路径中的节号。对于分段表,您需要将节/行组合转换为数据引用。

标准的方法是使用数组(例如dictionaryItems:[[Dictionary]])。这样,您可以通过使用外部数组上的索引路径部分和特定项来获取项目数组,方法是使用部分引用返回的数组上的索引路径行。

---使用需要在DictionaryTableViewController

中更改代码的方法进行更新
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // Assume a single section after a search
    return (searchController.active) ? 1 : sectionTitles.count
}


// Create a standard way to get a Dictionary from an index path
func itemForIndexPath(indexPath: NSIndexPath) -> Dictionary? {
    var result: Dictionary? = nil

    if searchController.active {
        result = searchResults[indexPath.row]
    } else {
        let wordKey = sectionTitles[indexPath.section]
        if let items = cockpitDict[wordKey] {
            result = items[indexPath.row]
        }
    }
    return result
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! DictionaryTableViewCell

    if let dictionary = itemForIndexPath(indexPath) {
        cell.wordLabel.text = dictionary.word
        cell.definitionSmallLabel.text = dictionary.definition
    } else {
        print("Cell error with path \(indexPath)")
    }

    return cell
}

 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showDictionaryDetail" {
        if let indexPath = tableView.indexPathForSelectedRow {
            let destinationController = segue.destinationViewController as! DictionaryDetailViewController
            if let dictionary = itemForIndexPath(indexPath) {
                destinationController.dictionary = dictionary
            } else {
                print("Segue error with path \(indexPath)")
            }
            searchController.active = false
        }
    }
}

答案 1 :(得分:1)

我检查了您的代码并认为麻烦在于destinationController.dictionary = (searchController.active) ? searchResults[indexPath.row] : dictionaryItems[indexPath.row]

你应该得到这样的字典(正如你在cellForRowAtIndexPath中所做的那样):

    let dictionary = (searchController.active) ? searchResults[indexPath.row]: dictionaryItems[indexPath.row]
    let wordKey = sectionTitles[indexPath.section]
    let items = cockpitDict[wordKey]

现在item将成为传递给详细视图的字典。

当我看到你在表格视图中非常有效地填充数据时,我明白了这个想法。

相关问题