Reputation: 3046
I have a UITableView
that populates custom cells based on incoming data:
var posts: [PostViewModel] = [] {
didSet {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
I'd like to insert a different custom cell that has nothing to do with the array i.e. a reminder for the user to subscribe or login. The Index Path set should look like this for example:
How would I go about this approach as the cell has nothing to do with the model.
Thanks.
Upvotes: 0
Views: 215
Reputation: 262
From my practice it is better to create custom type of cell. And add this type as a property to your PostViewModel. After that you can recognize what type of cell you should to dequeue. For example:
// Type of custom cell
enum PostsType {
case postCell
case loginCell
}
struct PostViewModel {
let type: PostsType
// another View model data
}
class ViewController: UITableViewController {
var posts: [PostViewModel] = [] {
didSet {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
posts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellType = posts[indexPath.row].type
switch cellType {
case .loginCell:
return tableView.dequeueReusableCell(withIdentifier: "LoginCell", for: indexPath)
case .postCell:
return tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath)
}
}
}
Upvotes: 2