2017-09-22 63 views
0

我試圖用兩個不同的原型單元格加載表格視圖。 profileCell應該只加載一次,並在表格視圖的頂部。 dogCell應該計算從firebase下載的dog個對象名爲dogs的數組。目前,只有第一個單元顯示正確。Swift:表視圖只返回一個單元格

我認爲numberOfRowsInSection方法不準確地計算狗數組中的狗對象。當我在return dogs.count + 1po dogs.count上放置一個斷點時,調試器繼續輸出0

當我使用return dogs.count表格視圖加載,但只有配置文件單元格。 「致命錯誤:索引超出範圍」

也許我需要改變我的tableview重新加載數據的方式,如果我使用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

爲什麼你在'viewDidLoad中一個'profileCell'局部變量()',如果你(正確)動態地'的tableView(獲得小區_,cellForRowAt: )'? – NRitH

+0

並且您是否已驗證從數據庫中返回預期的狗數量? – NRitH

+0

@NRitH很好!我不知道爲什麼在這個類中有一個profile元素屬性。我會刪除它。是的,我已經證實狗正在被正確地退回。感謝您的幫助。 –

回答

0

我居然找到了解決方法寫這個問題後不久,但我認爲這可能是有益的給別人看的。

因爲第一個indexPath.row專用於配置文件單元格,所以我不應該使用indexPath.row來導航我的dogs數組。相反,我應該使用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 
     } 

    } 
相關問題