简体   繁体   English

将自定义单元格插入 TableView

[英]Insert Custom Cell into TableView

I have a UITableView that populates custom cells based on incoming data:我有一个UITableView根据传入的数据填充自定义单元格:

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 ie a reminder for the user to subscribe or login.我想插入一个与数组无关的不同自定义单元格,即提醒用户订阅或登录。 The Index Path set should look like this for example:索引路径集应如下所示:

  1. Post Cell后细胞
  2. Post Cell后细胞
  3. Post Cell后细胞
  4. Login Cell登录单元
  5. Post Cell后细胞
  6. etc... ETC...

How would I go about this approach as the cell has nothing to do with the model.我将如何 go 关于这种方法,因为单元与 model 无关。

Thanks.谢谢。

From my practice it is better to create custom type of cell.根据我的实践,最好创建自定义类型的单元格。 And add this type as a property to your PostViewModel.并将此类型作为属性添加到您的 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)
        }
    }
}

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

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