Отображение 2 групп данных Firebase в разных ячейках - PullRequest
0 голосов
/ 06 декабря 2018

У меня есть база данных Firebase, структурированная так:

Screen Shot

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 разных перья, и я могу извлекать данные, но я не уверен, как структурироватьтест indexPath.row, чтобы строки моего табличного представления могли переключать стиль отображаемых ячеек в зависимости от того, к какой группе данных принадлежит массив.В настоящее время у меня есть тест со статической функцией if, но, очевидно, данные «песни» отображаются только после данных «post»

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
     }

   }

--------- EDIT ----------

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

1 Ответ

0 голосов
/ 06 декабря 2018

Возможно, вы хотите иметь одну временную шкалу с двумя типами элементов: Post и Song.Таким образом, один из способов сделать это будет иметь один суперкласс и два подкласса 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()
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...