Почему это не отображает информацию в UITableView? - PullRequest
1 голос
/ 21 июня 2020

Я был бы очень признателен за любую помощь по этому поводу. Я новичок в программировании, и пока мне не удалось реализовать эту функцию. Я хочу заполнить UITableViewCell информацией, полученной из Firestore, а именно: title, username и content. Мне удалось успешно распечатать массив title, но не удалось фактически заполнить его ячейками.

Это HomeViewController, где мой UITableView равен:

class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {


@IBOutlet weak var tableView: UITableView!

@IBOutlet weak var logoutButton: UIButton!


var postArray: [String] = []
var documents: [DocumentSnapshot] = []

let db = Firestore.firestore()
let currentUserID = Auth.auth().currentUser?.uid

    // Find the UserIDs of people following
// Where Field for those UserIDs in "Posts"


override func viewDidLoad() {
    super.viewDidLoad()
    getFollowingPosts()
    configureTableView()
    }

func getFollowingPosts() {
    let searchForFollowing = db.collection("users").document(currentUserID!).collection("Following")
    searchForFollowing.getDocuments { (snapshot, error) in
        for documents in snapshot!.documents {
            let followedUID = documents.get("uid")
            print(followedUID!)
            
            self.db.collection("posts").whereField("uid", isEqualTo: followedUID!).getDocuments { (querySnapshot, error) in
                for documents in querySnapshot!.documents {
                    let uid = documents.get("uid") as! String
                    let title = documents.get("Title") as! String
                    let ProfilePictureURL = documents.get("ProfilePictureURL") as! String
                    let username = documents.get("username") as! String
                    let content = documents.get("Content") as! String
                    self.postArray.append(title)
                    print(self.postArray)
                }
                self.tableView.reloadData()
            }
        }
    }
    }

func configureTableView() {
    tableView.delegate = self
    tableView.dataSource = self
    tableView.register(PostTableViewCell.self, forCellReuseIdentifier: "PostCell")

    // remove separators for empty cells
    tableView.tableFooterView = UIView()
    // remove separators from cells
    tableView.separatorStyle = .none
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! PostTableViewCell
    let post = postArray[indexPath.row]
    return cell
}

  

}

Это мой PostTableViewCell:

class PostTableViewCell: UITableViewCell {

@IBOutlet weak var usernameLabel: UILabel!

@IBOutlet weak var titleLabel: UILabel!

@IBOutlet weak var contentLabel: UILabel!


    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        addSubview(usernameLabel)
        addSubview(titleLabel)
        addSubview(contentLabel)

    }


    

}

Если бы кто-нибудь мог помочь, это было бы очень признательно. Как я уже сказал, я много боролся с этим.

1 Ответ

2 голосов
/ 21 июня 2020

Кажется, вы не устанавливаете данные на что-либо в ячейке.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! PostTableViewCell
    let post = postArray[indexPath.row]
    cell.titleLabel.text = post
    return cell
}

Кроме того, измените метод регистрации, если вы используете перо

func configureTableView() {
    //...
    tableView.register(UINib(nibName: "PostCell", bundle: nil), forCellReuseIdentifier: "PostCell")
    //...
}

Примечание : Убедитесь, что для файла пера установлен идентификатор пера как "PostCell".

...