2016-12-01 71 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。

相關問題