将数组从自定义单元格发送到另一个视图控制器

Posted

技术标签:

【中文标题】将数组从自定义单元格发送到另一个视图控制器【英文标题】:Send array from custom cell to another view controller 【发布时间】:2019-09-03 00:46:47 【问题描述】:

我正在对 Firebase 进行查询,结果显示在自定义单元格中。该单元格有一个 UIButton,当点击它时,它会转到另一个视图控制器,用户可以在其中输入信息。我的问题是,如何将自定义单元格中的数组发送到下一个视图控制器?我需要发送数组,以便我可以引用我将为每个数组添加的信息子集合。 Segue 工作正常,当我打印到控制台时,数组为空“nil”。任何帮助是极大的赞赏。

自定义单元格

import UIKit
import Firebase

protocol PatCellCommentsDelegate 
func patCommentBtnTapped (ptcomments: [Comment])


class PatdataCell: UITableViewCell 

@IBOutlet weak var ptnameLbl: UILabel!
@IBOutlet weak var dobLbl: UILabel!
@IBOutlet weak var finLbl: UILabel!
@IBOutlet weak var officemdLbl: UILabel!
@IBOutlet weak var assignedmdLbl: UILabel?
@IBOutlet weak var appnameLbl: UILabel!
@IBOutlet weak var assigneddateLbl: UILabel!
@IBOutlet weak var roomnumberLbl: UILabel?
@IBOutlet weak var diagnosesLbl: UILabel!
@IBOutlet weak var reasonforadmitorconsultLbl: UILabel!
@IBOutlet weak var goalofhospitalizationLbl: UILabel!
@IBOutlet weak var seenoseeLbl: UILabel?
@IBOutlet weak var notestocboLbl: UILabel!
@IBOutlet weak var numCommentsLbl: UILabel!
@IBOutlet weak var hospitalLbl: UILabel!
@IBOutlet weak var teamLbl: UILabel!
@IBOutlet weak var addCommentBtn: UIButton!

var ptdata: PTData!
var ptcomments = [Comment]()
var delegate: PatCellCommentsDelegate?

override func awakeFromNib() 
    super.awakeFromNib()


func configurePatDataCell(ptdata: PTData, delegate: 
PatCellCommentsDelegate) 

    self.ptdata = ptdata
    self.delegate = delegate
    ptnameLbl.text = ptdata.ptname
    dobLbl.text = ptdata.dob
    finLbl.text = ptdata.fin
    officemdLbl.text = ptdata.officemd
    assignedmdLbl?.text = ptdata.assignedmd
    appnameLbl.text = ptdata.app
    assigneddateLbl.text = ptdata.assigneddate
    roomnumberLbl?.text = ptdata.room
    diagnosesLbl.text = ptdata.diagnoses
    reasonforadmitorconsultLbl.text = ptdata.reasonforadmitorconsult
    goalofhospitalizationLbl.text = ptdata.goalofhospitalization
    seenoseeLbl?.text = ptdata.seenosee
    notestocboLbl.text = ptdata.notestocbo
    numCommentsLbl.text = ptdata.comments
    hospitalLbl.text = ptdata.hosp
    teamLbl.text = ptdata.team

    

  @IBAction func addCommentBtnTapped(_ sender: Any) 

   //trying to send data to commentsVC from this cell

   delegate?.patCommentBtnTapped(ptcomments: self.ptcomments)
  
  

视图控制器

import UIKit
import Firebase
import SVProgressHUD

class PatdataVC: UIViewController, UITableViewDelegate, 
UITableViewDataSource, PatCellCommentsDelegate 

@IBOutlet weak var patDataTableView: UITableView!

var ptdatas = [PTData]()
var ptComments = [Comment]()

override func viewDidLoad() 
    super.viewDidLoad()

    patDataTableView.delegate = self
    patDataTableView.dataSource = self
    patDataTableView.rowHeight = 1150



override func prepare(for segue: UIStoryboardSegue, sender: Any?) 
    if segue.identifier == "goToComments" 
        let commtsVC = segue.destination as! CommentsVC
        commtsVC.ptComments = ptComments
                SVProgressHUD.dismiss()
            
        

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


func tableView(_ tableView: UITableView, cellForRowAt indexPath: 
IndexPath) -> UITableViewCell 
    if tableView == patDataTableView 
        let cell = tableView.dequeueReusableCell(withIdentifier: 
"PatdataCell", for: indexPath) as? PatdataCell
        cell!.configurePatDataCell(ptdata: ptdatas[indexPath.row], 
delegate: self)
        return cell!
    
    return UITableViewCell()


func patCommentBtnTapped (ptcomments: [Comment]) 

    self.ptComments = ptcomments
    performSegue(withIdentifier: "goToComments", sender: self)



评论VC

import UIKit
import Firebase
import FirebaseFirestore 

class CommentsVC: UIViewController, UITableViewDelegate, 
UITableViewDataSource, CommentsDelegate 

@IBOutlet weak var commentTableView: UITableView!
@IBOutlet weak var addCommentTxt: UITextField!
@IBOutlet weak var keyboardView: UIView!

var ptComments = [Comment]()
var commentsPtData: Comment!
var commentRef: DocumentReference!
var username: String!
var commentListener : ListenerRegistration!
let firestore = Firestore.firestore()


override func viewDidLoad() 
    super.viewDidLoad()
    commentTableView.dataSource = self
    commentTableView.delegate = self
    commentTableView.rowHeight = 110

    //commentRef = 
firestore.collection(PTLIST_REF).document(commentsPtData.documentId)
    //        if let name = Auth.auth().currentUser?.displayName
    //            username = name
    //    

    self.view.bindToKeyboard()


override func viewDidAppear(_ animated: Bool) 
    commentListener = 

firestore.collection(PTLIST_REF).document(self.commentsPtData
.documentId)
        .collection(COMMENTS_REF)
        .order(by: TIMESTAMP, descending: false)
        .addSnapshotListener( (snapshot, error) in
            guard let snapshot = snapshot else 
                debugPrint("Error Fetching comments: \(Error.self)")
                return
            

            self.ptComments.removeAll()
            self.ptComments = Comment.parseData(snapshot: snapshot)
            self.commentTableView.reloadData()
        )


override func viewDidDisappear(_ animated: Bool) 
    commentListener.remove()


func commentOptionsTapped(commentsCellPtData: Comment) 
    let alert = UIAlertController(title: "Edit Comment", message: "You 
can delete or edit", preferredStyle: .actionSheet)
    let deleteAction = UIAlertAction(title: "Delete Comment", style: 
.default)  (action) in

        self.firestore.runTransaction( (transaction, errorPointer) -> 
Any? in

            let ptListDocument: DocumentSnapshot

            do 
                try ptListDocument = 

 transaction.getDocument(Firestore.firestore()
.collection(PTLIST_REF).document(self.commentsPtData.documentId))
             catch let error as NSError 
                debugPrint("Fetch Error: \ . 
(error.localizedDescription)")
                return nil
            

            guard let oldNumComments = ptListDocument.data()! 
 [NUM_COMMENTS] as? Int else  return nil 

            transaction.updateData([NUM_COMMENTS : oldNumComments - 
 1], forDocument: self.commentRef!)

            let commentRef =  
 self.firestore.collection(PTLIST_REF).document(self
 .commentsPtData.documentId).collection(COMMENTS_REF)
 .document(commentsCellPtData.documentId!)

            transaction.deleteDocument(commentRef)

            return nil
        )  (object, error) in
            if let error = error 
                debugPrint("transaction failed: \(error)")
             else 
                alert.dismiss(animated: true, completion: nil)
            
        
    

    let editAction = UIAlertAction(title: "Edit Comment", style: 
.default)  (action) in

        self.performSegue(withIdentifier: "toEditComment", sender: 
(commentsCellPtData, self.commentsPtData))
        alert.dismiss(animated: true, completion: nil)

    
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, 
handler: nil)

    alert.addAction(deleteAction)
    alert.addAction(editAction)
    alert.addAction(cancelAction)
    present(alert, animated: true, completion: nil)



@IBAction func addCommentTapped(_ sender: Any) 
    guard let commentTxt = addCommentTxt.text else  return 

    firestore.runTransaction( (transaction, errorPointer) -> Any? in

        let ptListDocument: DocumentSnapshot

        do 
            try ptListDocument = 
transaction.getDocument(Firestore.firestore()
.collection(PTLIST_REF).document(self.commentsPtData.documentId))
         catch let error as NSError 
            debugPrint("Fetch Error: \(error.localizedDescription)")
            return nil
        

        guard let oldNumComments = ptListDocument.data()! 
[NUM_COMMENTS] as? Int else  return nil 

        transaction.updateData([NUM_COMMENTS : oldNumComments + 1], 
forDocument: self.commentRef!)

        let newCommentRef = 
self.firestore.collection(PTLIST_REF).document((self
.commentsPtData.documentId)).collection(COMMENTS_REF).document()

        transaction.setData([
            COMMENT_TXT : commentTxt,
            TIMESTAMP : FieldValue.serverTimestamp(),
            USERNAME : self.username!,
            USER_ID : Auth.auth().currentUser?.uid ?? ""
            ], forDocument: newCommentRef)

        return nil
    )  (object, error) in
        if let error = error 
            debugPrint("transaction failed: \(error)")
         else 
            self.addCommentTxt.text = ""
            self.addCommentTxt.resignFirstResponder()
        
    


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



func tableView(_ tableView: UITableView, cellForRowAt indexPath: 
IndexPath) -> UITableViewCell 
    if let cell = tableView.dequeueReusableCell(withIdentifier: 
"CommentCell", for: indexPath) as? CommentCell 
        cell.configureCell(comment: ptComments[indexPath.row], 
delegate: self)
        return cell
    

    return UITableViewCell()


【问题讨论】:

可以分享一下commtsVC吗? 还有你要传递哪个数组? ptDatas 还是 ptComments? @NickStefanidis 我正在尝试传递 ptData。我添加了 CommetsVC 的代码。谢谢 你能告诉我确切的顺序吗,因为它有点乱。使用你的代码,你试图传递 ptComments 数组,如果我是正确的,这个数组是空的。 对不起,我还在学习中。我正在尝试将 ptData 从 PatDataCell 传递到 CommentsVC,因为我需要在 Firebase 中为 cmets 添加一个子集合。希望这是有道理的。这是截图drive.google.com/drive/folders/… 【参考方案1】:

在您的源代码中Custom Cell 中的ptcomments 属性未在任何地方设置,它在单元格中为空。

请为ptcomments设置正确的值

更新: 您尝试将self.comments = ptdata.commentsList 之类的行添加到功能configurePatDataCell

【讨论】:

嗨,如果我理解正确的话,我应该用 var ptcmets = [PTData]() 更改 var ptcmets = [Comment]() 吗? PTData 有我需要发送到另一个 VC 的数组。谢谢 @Eddie 也许你应该从你的数据源获取列表ptcomments(可能是ptdata)。当前,您只声明ptcomments没有设置值 正确的ptdata是数据源,当我点击UIButton时如何发送数据?我在哪里申报?我如何设置值?如果我很密集,我很抱歉,我还在学习。 @Eddie 你想传递什么样的数据? PTData[Comment]。你在哪里可以得到列表[Comment] 试图传递 PTData 中的信息。

以上是关于将数组从自定义单元格发送到另一个视图控制器的主要内容,如果未能解决你的问题,请参考以下文章

Swift - 从自定义单元格和单元格数据传递到另一个控制器

如何将选定的单元格发送到另一个视图控制器?

将 collectionView 数据发送到另一个视图控制器中的网点

将数据从自定义表格视图单元格传递到 UIView 控制器

从自定义单元格重新加载表格视图数据

将信息发送到另一个视图控制器