我正在创建一个iOS应用程序,该应用程序从Firebase数据库加载数据,然后创建包含该信息的UI表视图。我创建了一个带有重用标识符"cell"的原型单元格,以及一个带有标签的自定义单元格类。但是,当应用程序加载时,创建的单元格没有我为原型单元格创建的样式,即使可重用单元格与原型单元格具有相同的标识符也是如此。我无法更改原型单元格的标签文本,加载应用程序时我得到的只是具有默认单元格高度的空白行,而不是我添加到原型单元格的自定义项。
这是 UITableView 文件的代码
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var ref: DatabaseReference!
var postList = [Post]()
var refHandle : UInt!
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//let userID = Auth.auth().currentUser?.uid
ref = Database.database().reference().child("posts") //.child(userID)
tableView.register(PostTableViewCell.self, forCellReuseIdentifier: "cell")
fetchPosts()
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postList.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PostTableViewCell
//set cell content
let contentOfCellPost = postList[indexPath.row]
cell.title?.text = contentOfCellPost.post_words
return cell
}
func fetchPosts () {
let query = ref.queryOrdered(byChild: "timestamp").queryLimited(toFirst: 10)
query.observe(.value) { (snapshot) in
for child in snapshot.children.allObjects as! [DataSnapshot] {
if let value = child.value as? NSDictionary {
let post = Post()
let poster = value["poster"] as? String ?? "Name not found"
let post_content = value["post"] as? String ?? "Content not found"
post.post_words = post_content
post.poster = poster
self.postList.append(post)
DispatchQueue.main.async { self.tableView.reloadData() }
}
}
}
}
}
这是我为自定义单元格创建的类:
import UIKit
class PostTableViewCell: UITableViewCell {
@IBOutlet weak var title: UILabel!
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
}
}
但是,当我将可重用单元格属性更改为
cell.textLabel?.text = contentOfCellPost.post_words
我可以在表视图中看到文本,但它仍然不是基于我在情节提要中的原型单元格规范。
表视图的图像
如果您愿意,您错过了实现 heightForRowAt 或使用动态表查看单元格高度
你的问题是这一行:
tableView.register(PostTableViewCell.self, forCellReuseIdentifier: "cell")
如果为表视图注册一个类,则当您取消排队时,您将获得该类的空白单元格,而不是情节提要中的空白单元格。 因此,不会设置任何内容(IBOutlet,IBAction等(。
如果只想将情节提要(或 XIB 文件(中定义的原型单元取消排队,则无需注册它。
当您使用情节提要时,请从 viewDidLoad 函数中删除以下行。
tableView.register(PostTableViewCell.self, forCellReuseIdentifier: "cell")