2017-09-22 10 views
0

2つの異なるプロトタイプセルを持つテーブルビューを読み込もうとしています。 profileCellは、テーブルビューの一番上に一度だけロードする必要があります。 dogCelldogの配列を数え、firebaseからダウンロードしたdogsというオブジェクトをカウントする必要があります。現在、最初のセルだけが正しく表示されています。Swift:テーブルビューは1つのセルを返すだけです

私はnumberOfRowsInSectionメソッドがdogs配列のdogオブジェクトを正確に数えていないと思います。私がreturn dogs.count + 1po dogs.countにブレークポイントを置くと、デバッガは0を出力し続けます。

return dogs.countを使用すると、テーブルビューが読み込まれますが、プロファイルセルだけが読み込まれます。 return dogs.count + 1(上部のプロファイルセルを説明する)を使用すると、dogCellを構築するときに例外がスローされます。

おそらく、私のテーブルビューがデータを読み込む方法を変更する必要がありますか?

class DogTableViewController: UITableViewController { 

    var user = User() 
    let profileCell = ProfileTableViewCell() 
    var dogs = [Dog]() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let userDogRef = Database.database().reference().child("users").child(user.uid!).child("dogs") 

     let userProfileImageView = UIImageView() 
     userProfileImageView.translatesAutoresizingMaskIntoConstraints = false 
     userProfileImageView.widthAnchor.constraint(equalToConstant: 40).isActive = true 
     userProfileImageView.heightAnchor.constraint(equalToConstant: 40).isActive = true 
     userProfileImageView.layer.cornerRadius = 20 
     userProfileImageView.clipsToBounds = true 
     userProfileImageView.contentMode = .scaleAspectFill 
     userProfileImageView.image = UIImage(named: "AppIcon") 

     navigationItem.titleView = userProfileImageView 

     //MARK: Download dogs from firebase 
     userDogRef.observe(.childAdded, with: { (snapshot) in 
      if snapshot.value == nil { 
       print("no new dog found") 
      } else { 
       print("new dog found") 

       let snapshotValue = snapshot.value as! Dictionary<String, String> 
       let dogID = snapshotValue["dogID"]! 

       let dogRef = Database.database().reference().child("dogs").child(dogID) 
       dogRef.observeSingleEvent(of: .value, with: { (snap) in 
        print("Found dog data!") 
        let value = snap.value as? NSDictionary 
        let newDog = Dog() 

        newDog.name = value?["name"] as? String ?? "" 
        newDog.breed = value?["breed"] as? String ?? "" 
        newDog.creator = value?["creator"] as? String ?? "" 
        newDog.score = Int(value?["score"] as? String ?? "") 
        newDog.imageURL = value?["imageURL"] as? String ?? "" 
        newDog.dogID = snapshot.key 

        URLSession.shared.dataTask(with: URL(string: newDog.imageURL!)!, completionHandler: { (data, response, error) in 
         if error != nil { 
          print(error!) 
          return 
         } 
         newDog.picture = UIImage(data: data!)! 
         self.dogs.append(newDog) 
         DispatchQueue.main.async { 
          self.tableView.reloadData() 
         } 
        }).resume() 
       }) 
      } 
     }) 

     tableView.estimatedRowHeight = 454 
    } 

    // MARK: - Table view data source 

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return dogs.count + 1 
    } 

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     if indexPath.row == 0 { 
      let profileCell = tableView.dequeueReusableCell(withIdentifier: "profileCell", for: indexPath) as! ProfileTableViewCell 
      profileCell.nameLabel.text = user.name 
      profileCell.totalReputationLabel.text = String(describing: user.reputation!) 
      profileCell.usernameLabel.text = user.username 
      return profileCell 
     } else { 
      let dogCell = tableView.dequeueReusableCell(withIdentifier: "dogCell", for: indexPath) as! DogTableViewCell 
      dogCell.dogBreedLabel.text = dogs[indexPath.row].breed 
      dogCell.dogNameLabel.text = dogs[indexPath.row].name 
      dogCell.dogScoreLabel.text = String(describing: dogs[indexPath.row].score) 
      dogCell.dogImageView.image = dogs[indexPath.row].picture 
      dogCell.dogCreatorButton.titleLabel?.text = dogs[indexPath.row].creator 
      dogCell.dogVotesLabel.text = "0" 
      return dogCell 
     } 

    } 
} 
+0

あなたは(正しく) 'のtableView(_、cellForRowAtで動的にセルを取得する場合は、'のviewDidLoad() 'で' profileCell'ローカル変数を持っていない理由:ここで

は私が更新セクションです。 ) '? – NRitH

+0

そして、予想される犬の数がデータベースから返されたことを確認しましたか? – NRitH

+0

@NRitH良いキャッチ!私は、クラスにプロファイルセルプロパティがある理由を知りません。私はそれを削除します。そして、はい、私は犬が正しく返されていることを確認しました。ご協力ありがとうございました。 –

答えて

0

は私が実際にすぐにこの質問を書いた後、解決策を見つけたが、私は他の人が読むことのために役立つかもしれないと思う:

は、ここに私のコードです。

最初のindexPath.rowがプロファイルセル専用であるため、indexPath.rowを使用して犬の配列をナビゲートしてはいけません。代わりに、私は正しい犬のインデックスを取得するためにindexPath.row - 1を使用していたはずです。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     if indexPath.row == 0 { 
      let profileCell = tableView.dequeueReusableCell(withIdentifier: "profileCell", for: indexPath) as! ProfileTableViewCell 
      profileCell.nameLabel.text = user.name 
      profileCell.totalReputationLabel.text = String(describing: user.reputation!) 
      profileCell.usernameLabel.text = user.username 
      return profileCell 
     } else { 
      let dogCell = tableView.dequeueReusableCell(withIdentifier: "dogCell", for: indexPath) as! DogTableViewCell 
      dogCell.dogBreedLabel.text = dogs[indexPath.row - 1].breed 
      dogCell.dogNameLabel.text = dogs[indexPath.row - 1].name 
      dogCell.dogScoreLabel.text = String(describing: dogs[indexPath.row - 1].score) 
      dogCell.dogImageView.image = dogs[indexPath.row - 1].picture 
      dogCell.dogCreatorButton.titleLabel?.text = dogs[indexPath.row - 1].creator 
      dogCell.dogVotesLabel.text = "0" 
      return dogCell 
     } 

    } 
関連する問題