Katie H Katie H - 2 months ago 12
iOS Question

Hide element on select within table cell - Swift

I followed this app to build a table with custom cells: https://github.com/awseeley/Custom-Table-Cell

I am trying to expand a cell and show different content when the cell is clicked.

Here is what I have in my view controller:

var cellTapped:Bool = true
var currentRow = 0;

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//CODE TO BE RUN ON CELL TOUCH

let selectedRowIndex = indexPath
currentRow = selectedRowIndex.row

let cell:TblCell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TblCell

cell.image.hidden = true

tableView.beginUpdates()
tableView.endUpdates()

}



func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == currentRow {
if cellTapped == false {
cellTapped = true

return 141
} else {
cellTapped = false
return 70
}
}
return 70
}


The cell expands when it is clicked and shrinks when it is clicked again. But the image does not hide. How do I get the image to hide? Is there a better way to show another custom .xib file when the cell is selected and have an expand/collapse effect?

Answer
  1. You should add this implement below to your cellForRowAtIndexPath

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
        if indexPath.row == currentRow {
            if cellTapped == false {
                cell.image.hidden = false
            } else {
                cell.image.hidden = true
            }
        }
    
        return cell
    }
    

And didSelectRowAtIndexPath you should remove wrong code:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    //CODE TO BE RUN ON CELL TOUCH

    let selectedRowIndex = indexPath
    currentRow = selectedRowIndex.row
    tableView.reloadData()

}
  1. If you want use want use tableView.beginUpdate() for better animation, you can reference to my demo:

    Demo hide image on cell

Hope this help!

Comments