2016-12-01 9 views
0

私はミュージシャンに関する情報を取得するためにiTunes StoreからJSONを解析しています。一方、私はそのような辞書を受け取って、私のコンソールに印刷されている構文解析します。なぜTableViewは1つのセルだけを返しますか?

"resultCount": 50 

これは私のオブジェクトを返すメソッドです。しかし、辞書には50以上の要素が含まれており、プログラムは辞書の要素を1つだけ返します。

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

検索結果は辞書ですが、countメソッドを呼び出すと、"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、およびnilの値でテストされ、それぞれ1,50および1に戻されました。

関連する問題