简体   繁体   中英

Insert Custom Cell into TableView

I have a UITableView that populates custom cells based on incoming data:

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...

How would I go about this approach as the cell has nothing to do with the model.

Thanks.

From my practice it is better to create custom type of cell. And add this type as a property to your 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)
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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