簡體   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