ios - 将自定义单元格插入 TableView
问题描述
我有一个UITableView
根据传入数据填充自定义单元格:
var posts: [PostViewModel] = [] {
didSet {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
我想插入一个与数组无关的不同自定义单元格,即提醒用户订阅或登录。索引路径集应如下所示:
- 后细胞
- 后细胞
- 后细胞
- 登录单元
- 后细胞
- ETC...
由于单元格与模型无关,我将如何采用这种方法。
谢谢。
解决方案
根据我的实践,最好创建自定义类型的单元格。并将此类型作为属性添加到您的 PostViewModel。之后,您可以识别出应该使用哪种类型的单元格。例如:
// 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)
}
}
}
推荐阅读
- javascript - 如何在用户定义的所有路由之后在 NodeJS 中添加错误处理程序?
- vega-lite - 即使聚合函数是非总结性的,也会创建堆积条形图
- python - 基于ubuntu的docker容器中的python argparse
- c++ - C++ 宏包装一个外部函数并将其添加到一个类中
- node.js - 使用 AWS SES 发送群组电子邮件
- reactjs - 字体真棒图标不可点击(反应)
- python - 为什么尝试使用 matplotlib 绘制时间是 00:00?
- c# - 无法加载文件或程序集 'Microsoft.Owin, Version=2.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' 或其依赖项之一
- android-studio - Flutter 未检测到 Android Studio
- javascript - 如何获取我自己的 Google Drive 文件的 md5Checksum 字段(仅通过使用类和对象,没有 http-requests)?