首页 > 解决方案 > 将自定义单元格插入 TableView

问题描述

我有一个UITableView根据传入数据填充自定义单元格:

var posts: [PostViewModel] = [] {
        didSet {
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
    }

我想插入一个与数组无关的不同自定义单元格,即提醒用户订阅或登录。索引路径集应如下所示:

  1. 后细胞
  2. 后细胞
  3. 后细胞
  4. 登录单元
  5. 后细胞
  6. ETC...

由于单元格与模型无关,我将如何采用这种方法。

谢谢。

标签: iosswiftuitableview

解决方案


根据我的实践,最好创建自定义类型的单元格。并将此类型作为属性添加到您的 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)
        }
    }
}

推荐阅读