How to add two custom cell into tableview in story

2019-05-28 10:21发布

问题:

I have a tableView with two different custom cell. One cell have a switch and other a image, I have Two separated custom class for the cells, identifiers.. but I can't see this. i don't know if I need change the configuration in story board to dynamic or other thing.. Can I show two different custom cells

Thanks!

回答1:

Check the criteria for showing each specific custom cell, then cast to that cell as needed:

override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {

    if (criteria for cell 1) {
        let cell = tableView!.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as? Cell1
        return (cell)
    }
    else {
        let cell = tableView!.dequeueReusableCellWithIdentifier("cell2", forIndexPath: indexPath) as? Cell2
        return (cell)
    }
}

Swift 3

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath -> UITableViewCell {

    if (criteria for cell 1) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! Cell1
        return cell
    }
    else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as! Cell2
        return cell
    }
}


回答2:

 override func tableView(tableView: UITableView?,cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {

if (...) {
    let cell : Mycell1  = tableView!.dequeueReusableCellWithIdentifier("Mycell1", forIndexPath: indexPath) as? Mycell1
    return cell
}
else {
    let cell : Mycell2 = tableView!.dequeueReusableCellWithIdentifier("Mycell2", forIndexPath: indexPath) as? Mycell2
    return cell
   }
}