В пользовательской ячейке uitableview не отображаются все текстовые метки - PullRequest
0 голосов
/ 12 июня 2019

Я пытаюсь показать объект из базы данных в пользовательской ячейке. Он имеет три текстовых метки. Когда я запускаю свой код, он показывает только одну строку текста на ячейку, а не три, в виде таблицы. Возвращает только текстовую метку, которая является первой

Вот мой код для моего объекта Class:

class Class: NSObject {
var date_clasname: String?
var teacher: String?
var room_number: String?
init(dictionary: [String: Any]) {
    self.date_clasname = dictionary["date_clasname"] as? String ?? ""
    self.teacher = dictionary["teacher"] as? String ?? ""
    self.room_number = dictionary["room_number"] as? String ?? ""
}

}

Вот мой код для моего класса просмотра таблицы:

class classes_test_TableViewController: UITableViewController {
let cellId = "cellId"

var users = [Class]()

override func viewDidLoad() {
    super.viewDidLoad()

    //navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(handleCancel))

    tableView.register(UserCell.self, forCellReuseIdentifier: cellId)

    fetchClass()
}

func fetchClass() {
   // guard let uid = ?.user.uid
       // else{return}
    //let userID = Auth.auth().currentUser!.uid
    Database.database().reference().child("Science").observe(.childAdded, with: { (snapshot) in
        //print(userID)
        if let dictionary = snapshot.value as? [String: AnyObject] {
            let user = Class(dictionary: dictionary)
            self.users.append(user)
            print(snapshot)
            //this will crash because of background thread, so lets use dispatch_async to fix
            DispatchQueue.main.async(execute: {
                self.tableView.reloadData()
            })
        }

    }, withCancel: nil)
}

@objc func handleCancel() {
    dismiss(animated: true, completion: nil)
}

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

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

    // let use a hack for now, we actually need to dequeue our cells for memory efficiency
    //        let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: cellId)

    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)

    let Class = users[indexPath.row]
    cell.textLabel?.text = Class.date_clasname
    cell.textLabel?.text = Class.teacher
    cell.textLabel?.text = Class.room_number

    return cell
}

}

class UserCell: UITableViewCell {

override init(style: UITableViewCell.CellStyle, reuseIdentifier: 
String?) {
    super.init(style: .default, reuseIdentifier: reuseIdentifier)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
   }

 }

Вот моя структура базы данных:

"Science" : {
"-Lgxm6qJhzI2IIG4uary" : {
  "date_clasname" : "f",
  "room_number" : "d",
  "teacher" : "f"
}

Предполагается, что в ячейке показаны все три строки, но показана только одна.

1 Ответ

1 голос
/ 12 июня 2019

Вы используете стандарт UITableViewCell и назначаете все три значения одной и той же метке.

Вам необходимо привести ячейку к пользовательской ячейке и присвоить значения пользовательским меткам

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

    // let use a hack for now, we actually need to dequeue our cells for memory efficiency
    //        let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: cellId)

    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! UserCell

    let user = users[indexPath.row]
    cell.nameLabel?.text = user.date_clasname
    cell.teacherLabel?.text = user.teacher
    cell.roomLabel?.text = user.room_number

    return cell
}

Замените nameLabel, teacherLabel и roomLabel именами реальных свойств.

И, пожалуйста, соблюдайте соглашение об именах и имена переменных lowerCamelCased , например dateClasname и roomNumber

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...