2016-02-21 3 views
2

Я использую этот код, чтобы создать представление канала, которое показывает пользователей, изображения и комментарии, похожие на instagram. По какой-то причине ячейки в канале дублируют сообщения текущего пользователя. Не только это, но также помещает неправильное имя пользователя с изображениями на дубликаты ячеек. Что я делаю не так?Почему мои кормовые ячейки дублируются?

import UIKit 
import Parse 

class FeedTableViewController: UITableViewController { 

    var usersBeingFollowed = [String]() 
    var imageFiles = [PFFile]() 
    var imageComment = [""] 
    var usernames = [String]() 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     navigationItem.hidesBackButton = true 


     let getFollowedUsersQuery = PFQuery(className: "Followers") 

     getFollowedUsersQuery.whereKey("follower", equalTo: PFUser.currentUser()!.objectId!) 

     getFollowedUsersQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in 

      self.usernames.removeAll(keepCapacity: true) 
      self.imageComment.removeAll(keepCapacity: true) 
      self.imageFiles.removeAll(keepCapacity: true) 
      self.usersBeingFollowed.removeAll(keepCapacity: true) 

      if let objects = objects { 

       for object in objects { 

        let followedUser = object["following"] as! String 

        let getFollowedUsers = PFQuery(className: "Post") 

        getFollowedUsers.whereKey("userId", equalTo: followedUser) 

        let getCurrentUser = PFQuery(className: "Post") 
        getCurrentUser.whereKey("userId", equalTo: (PFUser.currentUser()?.objectId)!) 

        var query = PFQuery.orQueryWithSubqueries([getFollowedUsers,getCurrentUser]) 

        query.findObjectsInBackgroundWithBlock({ (imageObjects, error) -> Void in 


         if let objects = imageObjects { 

          for images in objects { 

           let userQuery = PFUser.query() 
           userQuery?.whereKey("_id", equalTo: images["userId"]) 
           userQuery?.findObjectsInBackgroundWithBlock({ (user, error) -> Void in 
            print(user) 
            if let user = user { 
             for username in user { 
              self.usernames.append(username["username"] as! String) 
             } 

            } 

           }) 

           self.imageFiles.append(images["imageFile"] as! PFFile) 
           self.imageComment.append(images["imageComment"] as! String) 
           self.tableView.reloadData() 


          } 

         } 

        }) 

       } 

      } 


     } 



    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    // MARK: - Table view data source 

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     // #warning Incomplete implementation, return the number of sections 
     return 1 
    } 

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     // #warning Incomplete implementation, return the number of rows 
     return usernames.count 
    } 


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let myCell = tableView.dequeueReusableCellWithIdentifier("imagePostCell", forIndexPath: indexPath) as! cell 

     if imageFiles.count > 0{ 
      myCell.userLabel.text = "\(usernames[indexPath.row]) completed the \(imageComment[indexPath.row]) challenge!" 
      imageFiles[indexPath.row].getDataInBackgroundWithBlock({ (data, error) -> Void in 
       if let downloadedImage = UIImage(data: data!) { 

        myCell.imagePost.image = downloadedImage 
//     self.tableView.reloadData() 

       } 
      }) 
     } 

     return myCell 
    } 
+1

Клетки повторно. После удаления ячейки вы должны очистить любой старый контент перед установкой нового содержимого – Paulw11

ответ

1

Это будет, очевидно, генерировать дублированный контент, потому что вы поставили условие, что if imageFiles.count > 0 затем будут отображаться данные.

Но что, когда нет изображений? Он определенно возьмет ценность от многоразового использования UITableViewCell. Проверьте ниже изменения:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let myCell = tableView.dequeueReusableCellWithIdentifier("imagePostCell", forIndexPath: indexPath) as! cell 

     if imageFiles.count > 0{ 
      myCell.userLabel.text = "\(usernames[indexPath.row]) completed the \(imageComment[indexPath.row]) challenge!" 
      imageFiles[indexPath.row].getDataInBackgroundWithBlock({ (data, error) -> Void in 
       if let downloadedImage = UIImage(data: data!) { 

        myCell.imagePost.image = downloadedImage 
//     self.tableView.reloadData() 

       } 
      }) 
     }else{ 

      myCell.userLabel.text = "Put What You Want Here" //make just nil 
      myCell.imagePost.image = UIImage(name: "placeholder.png") //Some Placeholder image when there is no data 
     } 
     return myCell 
    }