2016-12-01 72 views
0

我正在解析iTunes Store中的JSON以检索有关音乐家的信息。而解析我收到这样的字典,即打印到我的控制台。为什么TableView只返回一个单元格?

"resultCount": 50 

这是我的方法返回对象。但是,该字典包含超过50个元素,程序只返回字典中的一个元素。

extension SearchViewController: UITableViewDataSource { 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     if !hasSearched { 
      return 0 
     } 
     else if searchResults.count == 0 { 
      return 1 
     } else { 
      return searchResults.count 
     } 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

     if searchResults.count == 0 { 
      return tableView.dequeueReusableCell(withIdentifier: TableViewCellIdentifires.nothingFoundCell, for: indexPath) 

     } else { 
      let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCellIdentifires.searchResultCell, for: indexPath) as! SearchResultCell 

      let searchResult = searchResults[indexPath.row] 
      cell.nameLabel.text = searchResult.name 

      if searchResult.artistName.isEmpty { 
       cell.artistNameLabel.text = "Unknown" 
      } else { 
       cell.artistNameLabel.text = String(format: "%@ (%@)", searchResult.artistName, kindForDisplay(kind: searchResult.kind)) 
      } 

      return cell 
     } 
    } 

    func kindForDisplay(kind: String) -> String { 
     switch kind { 
     case "album": return "Album" 
     case "audiobook": return "Audio Book" 
     case "book": return "Book" 
     case "ebook": return "E-Book" 
     case "feature-movie": return "Movie" 
     case "music-video": return "Music Video" 
     case "podcast": return "Podcast" 
     case "software": return "App" 
     case "song": return "Song" 
     case "tv-episode": return "TV Episode" 
     default: return kind 
     } 
    } 



extension SearchViewController: UITableViewDelegate { 
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
     tableView.deselectRow(at: indexPath, animated: true) 
} 

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { 
    if searchResults.count == 0 { 
     return nil 
    } else { 
     return indexPath 
    } 
} 

} 

难道我错误地写了这种方法,或者我应该仔细观察另一个吗?

+0

你如何初始化'searchResults'?从代码的外观来看,可能会发现'searchResults.count = 0',并在'numberOfRows'方法中返回1。 – Frankie

回答

0

您的搜索结果是一本字典,但当您调用它的计数方法时,它不会返回您希望看到的值为"resultCount"

相反,在你行功能的数使用以下命令:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    if !hasSearched { 
     return 0 
    } 

    guard let count = searchResults["resultCount"], count > 0 else { 
     return 1 
    } 

    return count 
} 

新回电要么给你算,或默认值为1的结果,如果没有出现。

这是测试值为0,50和零并分别返回1,50和1。

相关问题