【问题标题】:components on my tableview cell are not visible我的表格视图单元格上的组件不可见
【发布时间】:2019-09-10 11:03:55
【问题描述】:

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

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

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

struct post {
   let name : String
} 

我已将数据从 firebase 推送到结构帖子。

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()
            }
        }
    }

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

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
    }

cellview.swift 设计如下

class cellview: UITableViewCell {


    @IBOutlet weak var programnames: UIButton!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

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

【问题讨论】:

  • @AamirR 但按钮的标签没有改变,只有一行可见。

标签: ios swift firebase tableview


【解决方案1】:

我发现有几件事可能会导致 UITableViewDataSource 无法被调用

  1. 需要在viewDidLoad中设置UITableView.dataSource = self
  2. 你需要在viewDidLoad注册cellview.xib,像这样:

    contents.register(UINib(nibName: "cellview", bundle: nil), forCellReuseIdentifier: "Cell")
    
  3. Optional 是因为它们可以是 nil,如果它这样做了,您的应用会崩溃,请避免强制展开 optionals !,这里是带有可选链接的示例 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()
    

【讨论】:

  • 你在数组posts中添加document.documentID,你能打印它包含的print(document.documentID)
  • 我做了,它给出了 firebase 数据库中文档的名称。 @AamirR
  • 是从插座更改按钮标签的语法是否正确。 @AamirR
  • 请注意这一行contents.register(UINib(nibName: "cellview", bundle: nil), forCellReuseIdentifier: "Cell")
猜你喜欢
  • 2018-07-22
  • 1970-01-01
  • 2013-05-26
  • 2011-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-31
相关资源
最近更新 更多