如何从viewcontroller访问tableview单元格的属性?

时间:2016-11-17 22:08:27

标签: swift uitableview

请看截图。 repliesTableView, replyTextField and replyButton中有一个ViewControllerrepliesTableView cell被称为ReplyCell。在ReplyCell中,有commentTableView列出该回复的所有评论,textfField, a commentButton添加新评论。

添加新回复和新评论时出现问题。当我点击comments array时,我想我需要在ReplyCell中将Reply button设为空。我怎样才能做到这一点?我不知道如何从根comments array访问ViewController

确切的问题:点击commentButton后,每个单元格中的所有注释都会翻倍。单击replyButton后,注释转到了错误的单元格。

enter image description here enter image description here

Code: 



import UIKit
import Firebase

class TopicForumVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {

@IBOutlet weak var topicNameLabel: UILabel!
@IBOutlet weak var replyNumberLabel: UILabel!

@IBOutlet weak var repliesTableView: UITableView!

@IBOutlet weak var replyTextField: UITextField!


var topicName:String?

var firstKey:String?

var secondKey:String?

var replies = [String]()

var replyButtonTapped = false

override func viewDidLoad() {
    super.viewDidLoad()

    repliesTableView.delegate = self
    repliesTableView.dataSource = self

    replyTextField.delegate = self

}

override func viewDidAppear(_ animated: Bool) {

    topicNameLabel.text = self.topicName

    loadReplies()
}

func loadReplies() {

    self.replies = []

    DataService.ds.Categories_Base.child(self.firstKey!).child("Topics").observe(.value, with:{(snapshot) in

        if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {

            for snap in snapshots {

                if let topicDict = snap.value as? Dictionary<String,AnyObject> {

                    if let topic = topicDict["text"] as? String {

                        if topic == self.topicName {

                            self.secondKey = snap.key

                            UserDefaults.standard.setValue(snap.key, forKey: Key_SecondKey)

                            if let replyDict = topicDict["replies"] as? Dictionary<String,AnyObject> {

                                for eachDict in replyDict {

                                    if let textDict = eachDict.value as? Dictionary<String,AnyObject> {

                                        if let reply = textDict["text"] as? String {

                                            self.replies.append(reply)
                                            self.replyNumberLabel.text = String(self.replies.count)
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            self.repliesTableView.reloadData()
        }

    })

}



func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return replies.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if let cell = tableView.dequeueReusableCell(withIdentifier: "ReplyCell") as? ReplyCell  {

         let reply = replies[indexPath.row]

           cell.configureReplyCell(reply: reply)

            return cell

    } else {

        return UITableViewCell()
    }

}


@IBAction func replyButtonTapped(_ sender: Any) {

    replyButtonTapped = true

    if let reply = replyTextField.text, reply != "" {

        self.replies = []

        DataService.ds.Categories_Base.child(self.firstKey!).child("Topics").child(self.secondKey!).child("replies").childByAutoId().child("text").setValue(reply)

        self.repliesTableView.reloadData()

        let i = replies.count

        for n in 0..<i {

            let indexPath = IndexPath(row: n, section: 1)

            let cell = repliesTableView.cellForRow(at: indexPath) as! ReplyCell

            cell.comments = []

            cell.repliesToReplyTableView.reloadData()


        }

        self.replyTextField.text = ""

        self.replyButtonTapped = false
    }

  }

}

 import UIKit
 import Firebase


class ReplyCell:    UITableViewCell,UITableViewDataSource,UITableViewDelegate, UITextFieldDelegate {


@IBOutlet weak var replyTextView: UITextView!

@IBOutlet weak var repliesToReplyTableView: UITableView!

@IBOutlet weak var commentTextField: UITextField!

var reply:String?

var comments = [String]()

var replyKey:String?

override func awakeFromNib() {
    super.awakeFromNib()

    self.comments = []

    repliesToReplyTableView.delegate = self
    repliesToReplyTableView.dataSource = self

    commentTextField.delegate = self

        loadComments()

}

func configureReplyCell(reply:String) {

    self.reply = reply

    self.replyTextView.text = self.reply
}

func loadComments() {

    self.comments = []

    if let firstKey = UserDefaults.standard.value(forKey: Key_FirstKey) as? String, let secondKey = UserDefaults.standard.value(forKey: Key_SecondKey) as? String {

        DataService.ds.Categories_Base.child(firstKey).child("Topics").child(secondKey).child("replies").observe(.value, with:{(snapshot) in

            if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {

                for snap in snapshots {

                    if let replyDict = snap.value as? Dictionary<String,AnyObject> {

                        if let reply = replyDict["text"] as? String {

                            if  reply == self.reply {

                                self.replyKey = snap.key

                                DataService.ds.Categories_Base.child(firstKey).child("Topics").child(secondKey).child("replies").child(snap.key).child("comments").observe(.value, with: { (commentSnapshot) in

                                    if let commentSnapshots = commentSnapshot.children.allObjects as? [FIRDataSnapshot] {

                                        for commentSnap in commentSnapshots {

                                            if let commentDict = commentSnap.value as? Dictionary<String,AnyObject> {

                                                if let comment = commentDict["text"] as? String {

                                                    self.comments.append(comment)

                                                }
                                            }
                                        }
                                    }

                                      self.repliesToReplyTableView.reloadData()

                                })
                            }
                        }
                    }
                }

            }

        })

    }

}


func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return comments.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let commentCell = tableView.dequeueReusableCell(withIdentifier:"CommentCell")

    commentCell?.textLabel?.text = comments[indexPath.row]

     return commentCell!
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)


}


@IBAction func commentBtnPressed(_ sender: Any) {

    if let comment = commentTextField.text, comment != "" {

        self.comments = []

        if let firstKey = UserDefaults.standard.value(forKey: Key_FirstKey) as? String, let secondKey = UserDefaults.standard.value(forKey: Key_SecondKey) as? String {

         DataService.ds.Categories_Base.child(firstKey).child("Topics").child(secondKey).child("replies").child(self.replyKey!).child("comments").childByAutoId().child("text").setValue(comment)

            if let myViewController = parentViewController as? TopicForumVC {

             //   myViewController.repliesTableView.reloadData()

                myViewController.replies = []
            }


            self.repliesToReplyTableView.reloadData()

            self.commentTextField.text = ""
            self.replyKey = ""
    }


  }

}

2 个答案:

答案 0 :(得分:1)

我真的不知道你正在建设的具体情况,但有两个想法可以提供一些指导。

1)如果您的表格显示来自数据源的内容,那么您可能会有某种参考。例如。加载单元格时(在这种情况下为CustomCell),您将执行类似get the index of the cellget the same index from the data以及put that data in the cells content的操作。如果是这种情况,您只需点击按钮就可以使用tableview.cellForRowAtIndexPath和发件人对象,然后从数据源中删除数组,例如tableDataSource[index] = nil并重新加载tableView。

2)如果您在CustomCell上有一个存储属性,您专门为存储此数组而添加,那么您将发送方对象转换为CustomCell并删除该属性,如Kim的答案所示。< / p>

希望这会有所帮助,但如果没有更多信息,那就很难说了。

答案 1 :(得分:0)

let cell = tableview.cellForRowAtIndexPath(...) as? CustomCell
if cell != nil {
     let arr = cell.array
}

BTW:我会重新考虑将你的数组存储在单元格中。