tableview单元上的组件不可见

时间:2019-04-20 14:11:37

标签: ios swift firebase tableview

我正在建立一个表格视图,其中仅包含一个带有不同标签的按钮。

我正在使用表格视图来显示按钮列表。

这是一个包含按钮名称的结构。

RequestParam

我已将数据从Firebase推送到结构后。

struct post {
   let name : String
} 

这些是表格视图的正常功能

var posts = [post]()
override func viewDidLoad() {
       super.viewDidLoad()
        let db = Firestore.firestore()
        db.collection(Auth.auth().currentUser?.uid as Any as! String).getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {
                   // print("\(document.documentID) => \(document.data())")
                    self.posts.insert(post(name: document.documentID), at: 0)
                }
                self.contents.reloadData()
            }
        }
    }

cellview.swift设计如下

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return posts.count
    }
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! cellview
        cell.programnames.titleLabel?.text = posts[indexPath.row].name
        return cell
    }

请告诉我我的错误。按钮“程序名称”在模拟器的表格视图中不可见

1 个答案:

答案 0 :(得分:0)

我看到一些遗漏的地方,可能导致UITableViewDataSource不被调用

  1. 您需要在UITableView.dataSource = self中设置viewDidLoad
  2. 您需要在cellview.xib中注册viewDidLoad,如下所示:

    contents.register(UINib(nibName: "cellview", bundle: nil), forCellReuseIdentifier: "Cell")
    
  3. 可选参数是因为它们可能是nil,如果这样做会导致您的应用崩溃,请避免强行拆开可选参数!,这是示例guard带有可选参数的语句链接

    guard err == nil, let documents = querySnapshot?.documents else {
        // error handling here
        return
    }
    
    self.posts = documents.map { post(name: $0.documentID) }
    
  4. 我在您的代码中看到了使用posts.insert(..., at: 0)的方法,如果有意使用以下命令,它将颠倒该数组:

    self.posts = documents.map({ post(name: $0.documentID) }).reversed()