Search code examples
iosswifttableviewstackview

Swift 3 Table View - Remove Stack View from some cells


I've got table view cells which contain, amongst other things, a stack view. The stack view should only be in a cell, if some requirements are true. If not, then the height of the cell should be reduced. When I use .isHidden, the height stays the same. But I want the stack view to be removed from that cell.

Here's my code:

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "RumCell", for: indexPath) as! RumCell

    let currentRum: Rum
    currentRum = rumList[indexPath.row]

    cell.rum = currentRum

    if (cell.rum?.clubRatingJuicy == 0) && (cell.rum?.clubRatingGasy == 0) && (cell.rum?.clubRatingSpicy == 0) && (cell.rum?.clubRatingSweet == 0) {
        cell.frame.size.height -= 76
    }

    return cell
}

As you can see, I tried to reduce the cell height, but this doesn't work. I also tried this, which doesn't work:

    if (cell.rum?.clubRatingJuicy == 0) && (cell.rum?.clubRatingGasy == 0) && (cell.rum?.clubRatingSpicy == 0) && (cell.rum?.clubRatingSweet == 0) {
        cell.tastStack.removeFromSuperview()
    }

Can anyone please tell me how to do this?


Solution

  • you should use different cell prototypes RumCell (without stackview) and RumCellDetailed (with stackview) which both conform to a protocol RumCellProtocol (where you can set the rum var)

    protocol RumCellProtocol {
        func config(rum: Rum)
    }
    

    and this code:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        var cellIdentifier = "RumCellDetailed"
    
        if (cell.rum?.clubRatingJuicy == 0) && (cell.rum?.clubRatingGasy == 0) && (cell.rum?.clubRatingSpicy == 0) && (cell.rum?.clubRatingSweet == 0) {
            cellIdentifier = "RumCell"
        }
    
    
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! RumCellProtocol
    
        let currentRum: Rum
        currentRum = rumList[indexPath.row]
    
        cell.config(rum: currentRum)
    
        return cell
    }