我有一个结构如下的 Firebase 数据库:
var posts = [Post]()
var songs = [Song]()
override func viewDidLoad() {
super.viewDidLoad()
let cellNib = UINib(nibName: "PostTableViewCell", bundle: nil)
tableView.register(cellNib, forCellReuseIdentifier: "postCell")
let songNib = UINib(nibName: "SongTableViewCell", bundle: nil)
tableView.register(songNib, forCellReuseIdentifier: "songCell")
我有 2 个不同的 Nib 并且能够提取数据,但我不确定如何构建 indexPath.row 测试,以便我的 TableView 行可以根据数组所属的数据组切换它显示的单元格样式到。我目前有一个静态 if 函数的测试,但显然只在“发布”数据之后显示“歌曲”数据
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count + songs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row < posts.count {
let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
cell.set(post: posts[indexPath.row])
return cell
} else {
let cell2 = tableView.dequeueReusableCell(withIdentifier: "songCell", for: indexPath) as! SongTableViewCell
cell2.set(song: songs[indexPath.row-posts.count])
return cell2
}
}
--------编辑------------
class Post:Item {
var imageURL: String!
convenience init(id: String, author: UserProfile, text: String, timestamp: Double, imageURL: String) {
self.init(id: id, author: author, text: text, timestamp: timestamp, imageURL: imageURL)
self.imageURL = imageURL
}
}
或
class Post:Item {
var imageURL: String!
init(id: String, author: UserProfile, text: String, timestamp: Double, imageURL: String) {
super.init(id: id, author: author, text: text, timestamp: timestamp)
self.imageURL = imageURL
}
}
最佳答案
您可能希望一个时间轴包含两种类型的项目:Post
和 Song
。
因此,一种方法是拥有一个父类(super class)和两个子类 Post
和 Song
class Item
author
timestamp
... other common properties
class Post: Item
text
...
class Song: Item
songName
...
然后你可以只拥有 Item
对象的数组
var items = [Item]()
然后不是将帖子和歌曲附加到帖子和歌曲数组,而是将它附加到 items
数组。
您还可以按timestamp
属性对项目数组进行排序
items.sorted(by: { $0.timestamp > $1.timestamp })
最后在 numberOfRowsInSection
数据源方法中只返回项目数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
并且在 cellForRowAt
数据源方法中设置单元格取决于项目是 Song
还是 Post
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = items[indexPath.row]
if let song = item as? Song {
let cell = tableView.dequeueReusableCell(withIdentifier: "songCell", for: indexPath) as! SongTableViewCell
cell.set(song: song)
return cell
} else if let post = item as? Post {
let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
cell.set(post: post)
return cell
} else {
return UITableViewCell()
}
}
关于ios - 在不同的 cell nibs 中显示 2 组 Firebase 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53658307/