繁体   English   中英

将自定义单元格插入 TableView

[英]Insert Custom Cell into TableView

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

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

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

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

我将如何 go 关于这种方法,因为单元与 model 无关。

谢谢。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM