2016-11-20 8 views
0

私は、各セルに一度に1つずつ表示された画像を持つInstagramのようなフィードを持っています。あなたはそれらを押してcommentTBVに行くことができます。投稿の下にコメントがあり、このビューで正しくカウントされます。フィード内のコメントの数を表示

var commentsArray = [FotoComment]() 

is the array holding the comments 

kommentarArrayは私がカウントの量を表示するためにそれを使用することができるようにassignArrayのFUNCでいっぱいにしたい配列です。

var kommentarArray = [FotoComment]() 

[FotoComment]私は私が欲しい私のコメント

に使用する私のSTRUCはすでにフィードにcommentArray.countコメントの正しい番号が表示されますことです。

func assignArray() { 
    let otherVC = CommentTableViewController() 
    kommentarArray = otherVC.commentsArray 

プリント(kommentarArray.count) }

私はCommentTBVCのコメントの配列への私のフィードからのアクセスを得るこの方法です。

cell.kommentarZähler.text = "Kommentare: \(kommentarArray.count)" 

しかし、それはすでに5件のコメントを持っており、それが正しくCommentTBVに表示されていても、それは常に0を示しています

私の細胞です。

import UIKit 

インポートFirebase インポートFirebaseAuth インポート

クラスMemesTableViewController FirebaseDatabase MemesTableViewConbtroller(供給)するための

M完全なコード:のUITableViewController {

var kommentarArray = [FotoComment]() 
var dataBaseRef : FIRDatabaseReference! 
var storageRef : FIRStorageReference! 
var posts = [PostMitBild]() 
var segmentedControl : HMSegmentedControl! 





override func viewDidLoad() { 
    super.viewDidLoad() 
    assignArray() 


segmentedControl = HMSegmentedControl(sectionTitles: ["Top Heute", "Beliebteste", "Neue"]) 
    segmentedControl.frame = CGRect(x: 10, y: 10, width: 300, height: 60) 
    segmentedControl.backgroundColor = UIColor.red 
    segmentedControl.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] 
    segmentedControl.borderColor = UIColor.brown 
    segmentedControl.tintColor = UIColor.black 
    segmentedControl.selectionIndicatorColor = UIColor.gray 


    segmentedControl.addTarget(self, action: #selector(getter: MemesTableViewController.segmentedControl), for: UIControlEvents.valueChanged) 
    tableView.tableHeaderView = segmentedControl 

segmentedAction() 
} 



func segmentedAction() { 
    if segmentedControl.selectedSegmentIndex == 0 { 



     let postRef = FIRDatabase.database().reference().child("MemesBilder") 


     postRef.observe(.value, with: { (snapshot) in 
      var newPost = [PostMitBild]() 
      for post in snapshot.children { 

       let Post = PostMitBild(snapshot: post as! FIRDataSnapshot) 
       newPost.insert(Post, at: 0) 

      } 

      self.posts = newPost 
      DispatchQueue.main.async { 

       self.tableView.reloadData() 


      } 

      }, withCancel: { (error) in 
       print(error.localizedDescription) 
     }) 



    } 

} 



//------------------------------------------ 


override func viewWillAppear(_ animated: Bool) { 


    if FIRAuth.auth()?.currentUser == nil { 

     let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Login") 
     self.present(vc, animated: true, completion: nil) 


    } 


} 






override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell 

    if let seconds = posts[indexPath.row].postDate { 
     let timestamp = NSDate(timeIntervalSince1970: seconds) 

     let dateFormatter = DateFormatter() 
     dateFormatter.dateFormat = "dd/MM/yyyy HH:mm" 
     cell.uploadDatum.text = dateFormatter.string(from: timestamp as Date) 


    } 

     cell.kommentarZähler.text = "Kommentare: \(kommentarArray.count)" 
     cell.usernameTextField.text = posts[indexPath.row].username 
     cell.postContent.text = posts[indexPath.row].content 



     storageRef = FIRStorage.storage().reference(forURL: posts[indexPath.row].userImageUrlString) 
     storageRef.data(withMaxSize: 1 * 1024 * 1024, completion: { (data, error) in 
      if error == nil { 
       DispatchQueue.main.async { 
        if let data = data { 
         cell.UserImageView.image = UIImage (data: data) 
        } 
       } 

      }else { 
       print(error?.localizedDescription) 
      } 
     }) 

     let storageRef2 = FIRStorage.storage().reference(forURL: posts[indexPath.row].PostImageUrlString) 
     storageRef2.data(withMaxSize: 1 * 1024 * 1024, completion: { (data, error) in 
      if error == nil { 
       DispatchQueue.main.async { 
        if let data = data { 

         cell.postImageView.image = UIImage (data: data) 
        } 

       } 
      }else { 
       print(error?.localizedDescription) 
      } 
     }) 

     return cell 



} 



//done!!!! ------------------------------------------ 


override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
    if editingStyle == .delete { 
     tableView.deleteRows(at: [indexPath], with: .fade) 


     let ref = posts[indexPath.row].ref 
     ref!.removeValue() 

     posts.remove(at: indexPath.row) 
     tableView.deleteRows(at: [indexPath], with: .fade) 

    } 
} 




override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    var numberOfRows = 0 
    switch segmentedControl.selectedSegmentIndex { 
    case 0 : numberOfRows = posts.count 

    case 1: numberOfRows = posts.count 

    default: break 


    } 

    return numberOfRows 
} 


override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
    return 420.00 
} 




override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    if segmentedControl.selectedSegmentIndex == 0 { 
     if segue.identifier == "addComment" { 
      let vc = segue.destination as! CommentTableViewController 
      let indexPath = tableView.indexPathForSelectedRow! 

      vc.selectedPosts = posts[indexPath.row] 
     } 

    } 
} 


override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    if segmentedControl.selectedSegmentIndex == 0 { 
     performSegue(withIdentifier: "addComment", sender: self) 
    } 
    if segmentedControl.selectedSegmentIndex == 1 { 
     performSegue(withIdentifier: "addComment", sender: self) 
    } 
    if segmentedControl.selectedSegmentIndex == 2 { 
     performSegue(withIdentifier: "addComment", sender: self) 
    } 
} 

func assignArray() { 

    let otherVC = CommentTableViewController() 
    kommentarArray = otherVC.commentsArray 

    print(kommentarArray.count) 
} 

}

import UIKit 

輸入Firebase 輸入FirebaseAuth インポートFirebaseDatabase 輸入FirebaseStorage(私はすでにこのテーブルビューに取り組んでいる配列VAR commentsArray = FotoCommentからのコメントの数を取得したい)CommentTableViewControllerためのコード

クラスCommentTableViewController:のUITableViewController {

@IBOutlet weak var komentarZähler: UILabel! 




@IBOutlet weak var UserImageView: UIImageView! 
@IBOutlet weak var usernameTextField: UILabel! 
@IBOutlet weak var postImageView: UIImageView! 
@IBOutlet weak var postContent: UITextView! 



var dataBaseRef : FIRDatabaseReference! 
var storageRef : FIRStorageReference! 
var commentsArray = [FotoComment]() 
var selectedPosts:PostMitBild! 



override func viewDidLoad() { 
    super.viewDidLoad() 

    configurePost() 




    let commentRef = selectedPosts.ref!.child("Kommentare") 

    commentRef.observe(.value, with: { (snapshot) in 
     var newComments = [FotoComment]() 
     for item in snapshot.children { 
      let neuerKommentar = FotoComment(snapshot: item as! FIRDataSnapshot) 
      newComments.insert(neuerKommentar, at: 0) 

     } 
     self.commentsArray = newComments 
     self.tableView.reloadData() 

     }, withCancel: { (error) in 
      print(error.localizedDescription) 
    }) 


} 
@IBAction func addComment(_ sender: UIBarButtonItem) { 

    let alertView = UIAlertController(title: "Kommentar", message: "Füge einen Kommentar hinzu", preferredStyle: UIAlertControllerStyle.alert) 
    alertView.addTextField { (textfield) in 
     textfield.placeholder = "Einen neuen Kommentar hinzufügen" 

    } 


    let sendCommentAction = UIAlertAction(title: "Kommentieren", style: .default) { (action) in 
     let textfield = alertView.textFields!.first! 

     let comment = FotoComment(content: textfield.text! , postId: self.selectedPosts.postId , username: (FIRAuth.auth()!.currentUser!.displayName!) , userImageUrlString: String(describing: FIRAuth.auth()!.currentUser!.photoURL!), postDate: (NSDate().timeIntervalSince1970)) 

     let commentRef = self.selectedPosts.ref!.child("Kommentare").childByAutoId() 
     commentRef.setValue(comment.toAnyObject()) 
    } 


    let cancelAction = UIAlertAction(title: "Abbrechen", style: .cancel, handler: nil) 
    alertView.addAction(sendCommentAction) 
    alertView.addAction(cancelAction) 
    self.present(alertView, animated: true, completion: nil) 

} 


// 2---------------------------------------------- 

func configurePost() { 

    usernameTextField.text = selectedPosts.username 
    postContent.text = selectedPosts.content 


    storageRef = FIRStorage.storage().reference(forURL: selectedPosts.userImageUrlString) 
    storageRef.data(withMaxSize: 1 * 1024 * 1024, completion: { (data, error) in 
     if error == nil { 
      DispatchQueue.main.async { 
       if let data = data { 
        self.UserImageView.image = UIImage (data: data) 
       } 
      } 

     }else { 
      print(error?.localizedDescription) 
     } 
    }) 
    let storageRef2 = FIRStorage.storage().reference(forURL: selectedPosts.PostImageUrlString) 
    storageRef2.data(withMaxSize: 1 * 1024 * 1024, completion: { (data, error) in 
     if error == nil { 
      DispatchQueue.main.async { 
       if let data = data { 

        self.postImageView.image = UIImage (data: data) 
       } 

      } 
     }else { 
      print(error?.localizedDescription) 
     } 
    }) 

} 






override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     komentarZähler.text = "Kommentare: \(commentsArray.count)" 
    return commentsArray.count 


} 

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "commentCell", for: indexPath) as! CommentTableViewCell 

    if let seconds = commentsArray[indexPath.row].postDate { 
     let timestamp = NSDate(timeIntervalSince1970: seconds) 

     let dateFormatter = DateFormatter() 
     dateFormatter.dateFormat = "dd/MM/yyyy HH:mm:ss" 
     cell.uploadDatum.text = dateFormatter.string(from: timestamp as Date) 


    } 



    cell.usernameTextField.text = commentsArray[indexPath.row].username 
    cell.postContent.text = commentsArray[indexPath.row].content 


    storageRef = FIRStorage.storage().reference(forURL: commentsArray[indexPath.row].userImageUrlString!) 
    storageRef.data(withMaxSize: 1 * 1024 * 1024, completion: { (data, error) in 
     if error == nil { 
      DispatchQueue.main.async { 
       if let data = data { 
        cell.UserImageView.image = UIImage (data: data) 
       } 
       self.tableView.reloadData() 
      } 


     }else { 
      print(error?.localizedDescription) 
     } 



    }) 

リターンセル }

}

this is how i safe my data in firebase. I want to update the number of comments (kommentarAnzahl which is currently 0) every time a comment is added to the post

+0

あなたの主な配列はどれですか?あなたは 'kommentarArray'と' commentsArray'の2つの配列を持っています。あなたの関数は次の配列にコピーしているように見えますから、同じデータを保持する2つの配列があります。私の推測は 'commentsArray'ですので、あなたのセルのテキストとしてカウントし、 'assignArray'関数を取り除きます – eshirima

+0

私のメイン配列はすべてのコメントを保持しています:var commentsArray = [FotoComment]()。 KommentarArrayはfeedTBVにあり、カウントを取得しようとする場所があります。私は同じデータをkommentarArray(新しいもの)とcommentsArray(正しい数のコメントを保持しているもの)に持っていこうとしていますが、カウントすると0を表示しています。 –

+0

とあなたのコンテンツを印刷するために使用するものは何ですか? – eshirima

答えて

0

あなたのアレイ数がセルに表示する文字列値に変換する必要があります。

は、私はこれがあなたのために働くことを願っています

cell.kommentarZähler.text = String("Kommentare:",kommentarArray.count) 

、このコードを試してみてください。

+0

残念ながら、それは私のためにうまくいかない:/。また、initがinitに改名された(という記述:)。私はまだそれは動作しません変更しました。 –

+0

あなたが使っている速いバージョン? –

+0

私はスイフトを使用しています3.0 –

0

CommentTableViewControllerMemesTableViewControllerという2つの別個のビューコントローラがあるので、commentsArraykommentarArrayがあります。これらの配列はクラススコープのもので、クラスの外に出ると意味があります。この場合、ビューを離れることになり、割り当てが解除されます。ビューに入ると、再び作成され、値で埋められます。

あなたはcommentsArrayの要素数を取得したいので、私はあなたがこれを追跡し続けるだろう静的変数を作成お勧めします。静的なものを作成すると、アプリケーション/プログラム全体にアクセスできるようになり、変更はアプリケーション全体に反映されます。つまり、変数を格納するためにメモリブロックが予約されています。この変数は、アプリケーションを完全に終了すると割り当て解除されます。これをアプリスコープ変数と考えることができます。

二つの方法

  1. みじめな道

    var commentsArray = [FotoComment]()からstatic var commentsArray = [FotoComment]()にごcommentsArray定義を変更し

    。これを行うと、この配列の内容に他のクラスからアクセスして操作することができます。要素数が少ない場合は素晴らしいですが、何万、何百万というコメントがあるとどうなりますか?それは、私たちが本当に必要としないときでも、膨大な量のデータをどこにでも持ち歩くことを意味します。

  2. 推奨方法

    現在commentsArray定義を保ち、あなたのCommentTableViewController内のこのstatic var numberOfComments: Int = 0を追加します。その後

    CommentTableViewController.numberOfComments = commentsArray.count 
    

下に示すように、あなたが戻ってあなたMemesTableViewControllerに行くとき右commentsArrayにあなたの要素を追加した後、要素トラッカーを更新し、あなたは単にassignArray()を削除することができます。私たちは今、グローバル要素のカウンタを持っており、単にこれにより、この

cell.kommentarZähler.text = String(CommentTableViewController.numberOfComments) 

にあなたのセルを修正するので、あなたはFriendsVCと呼ばれる別のクラスを言う作成する場合でも、あなたはまだnumberOfCommentsにアクセスしても、同様にそれを変更することができます。

PS:いつでもどこでもあなたがそれにアクセスしたり、修正したいnumberOfCommentsあなたは、MUSTstaticあるので、常に最初にそれがで定義されたクラスまたは構造体を呼び出して、このケースでは、それはとてもCommentTableViewControllerの内側にあります。アクセスするには常にCommentTableViewController.numberOfCommentsを実行する必要があります。たとえあなたが内部にいてもCommentTableViewControllerそのものです。常にそれを覚えています。

+0

お返事ありがとう!これはちょっとした作品です。つまり、1つの画像(例:3)からのみコメントの数を表示し、別のもの(例えば:1)を押して何も変わらない1つのコメント(今2)を追加すると、すべてのセルに対して2つのコメントが表示されます。私はそれを各細胞に特異的にする必要がある。 –

+0

と私はAppでビューを入力すると、それは常に0のカウントで始まるだけ私は特定のセル –

+0

@Zash__に押された後、私は本当にあなたがそのGIFのように投稿しmean..Canかを理解していない変更問題を視覚化するか?プラス私の答えがあなたの最初の問題を解決した場合は、投票して答えとして受け入れてください:) – eshirima

関連する問題