Я хочу получить данные о пожарном хранилище в dequeueReusableCell - PullRequest
0 голосов
/ 20 декабря 2018

Я переписал весь текст, и теперь я получил код, который хотел реализовать.Он не может быть отображен на tableCell, и компоновка также разрушается.Я сожалею, что код и написанное мной тело недостаточно объяснены.

guard let userID = Auth.auth ().текущий пользователь?.uid Я хочу всегда получать идентификатор пользователя с помощью else {return}.

// guard let docSnapshot = querySnapshot, document.exists else {return}

Поскольку ошибка происходит, она закомментируется,

В пределах viewidLoad UIViewController

var profDict: [ProfDic] = [] находится в UIViewController.

profUIView добавляется в UIViewController.

    func getFirebaseData() {

         db = Firestore.firestore()

        guard let userID = Auth.auth().currentUser?.uid else {return}


        let ref = db.collection("users").document(userID)

        ref.getDocument{ (document, error) in

            if let document = document {
//                guard let docSnapshot = querySnapshot, document.exists else {return}
                if let prof = ProfDic(dictionary: document.data()!) {

                    self.profDict.append(prof)

                    print("Document data \(document.data())")
                }
            }else{
                print("Document does not exist")
            }

            self.profUIView.tableView1.reloadData()
        }

    }

tableView1 был добавлен в ProfUIView.

class ProfUIView: UIView, UITableViewDelegate, UITableViewDataSource {

        //omission...

            override init(frame: CGRect) {
                super.init(frame: frame)

                backgroundColor = .blue

                addSubview(tableView1)
                tableView1.anchor(top:  //omission...

                 sections = [
                    Section(type: .prof_Sec, items: [.prof]),
                    Section(type: .link_Sec, items: [.link]),
                    Section(type: .hoge_Sec, items: [.hoge0])
                ]

                tableView1.register(TableCell0.self, forCellReuseIdentifier: TableCellId0)                  
                tableView1.register(TableCell3.self, forCellReuseIdentifier: TableCellId3)                    
                tableView1.register(TableCell5.self, forCellReuseIdentifier: TableCellId5)    



                tableView1.delegate = self
                tableView1.dataSource = self

             }

             var tableView1:UITableView = {
                 let table = UITableView()
                 table.backgroundColor = .gray
                 return table
             }()

             //omission                

             func numberOfSections(in tableView: UITableView) -> Int {
                  return sections.count
             }

             func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                  return (baseVC?.profDict.count)!//sections[section].items.count
             }                        

             func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {                            
                switch sections[indexPath.section].items[indexPath.row] {                                
                   case .prof:
                       let cell0 = tableView.dequeueReusableCell(withIdentifier: TableCellId0, for: indexPath) as? TableCell0                                
                       cell0?.nameLabel.text = baseVC?.profDict[indexPath.row].userName 
                       return cell0!
               }

              //omission...   
            }   
        }

Дополнительные примечания

import Foundation
import FirebaseFirestore

struct ProfDic {

    var userName :String

    var dictionary:[String:Any] {
        return
            ["userName" : userName

        ]
    }

}


extension ProfDic {

    init?(dictionary:[String:Any]) {

        guard let userName = dictionary["userName"] as? String
        else {return nil}

        self.init(userName: userName as String)

    }

}

введите описание изображения здесь

1 Ответ

0 голосов
/ 24 декабря 2018

Сначала создайте пустой массив из ProfDic элементов:

var profDict: [ProfDic] = []

Затем создайте функцию для загрузки ваших данных Firebase:

func getFirebaseData() {

    db = Firestore.firestore()
    let userRef = db.collection("users").getDocuments() {
        [weak self] (querySnapshot, error) in
        for document in querySnapshot!.documents {
            guard let docSnapshot = docSnapshot, docSnapshot.exists else {return}

            if let prof = ProfDic(dictionary: docSnapshot.data()!) {
                profDict.append(prof)
            }
        }
    tableView.reloadData()
    }
}

Вызовите этофункция in viewDidLoad или viewDidAppear.

Затем в tableView cellForRowAt вы получаете доступ к своим данным следующим образом:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    switch sections[indexPath.section].items[indexPath.row] {
    case .prof:
        let cell = tableView.dequeueReusableCell(withIdentifier: TableCellId, for: indexPath) as? TableCell
        cell?.nameLabel.text = profDict[indexPath.row].userName
        return cell!
    }
}

РЕДАКТИРОВАТЬ: Также в numberOfRowsInSection:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return profDict.count
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...