Search code examples
iosarraysswiftuitableviewcell

Disabling all UITableView cells except the last one - Swift


Currently working with UITableView in swift.

Since my table cell values are appending by clicking the button i want to figure out a way to disable interaction for all the previous cells, except the last one.

I've played with array-based approach a little, but it didn't work out the way i wanted.

var disabledRows = [0,1,2]
        else
    {
        cell.backgroundColor = UIColor.orangeColor()
    }

    if (contains(disabledRows, indexPath.row)) {
        cell.userInteractionEnabled = false
    }
    else {
        cell.userInteractionEnabled = true
    }

The issue with this approach is that i have to count all cells and then block the last one.

Maybe there are some easier approaches?

Any help much appreciated.

Update - here is my complete "cellForRowAtIndexPath" function

func tableView(tableView: UITableView, cellForRowAtIndexPath
    indexPath: NSIndexPath) -> UITableViewCell
{
    let cell: CustomCellForTableViewTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! CustomCellForTableViewTableViewCell

    if indexPath.row % 2 == 0
    {
        cell.backgroundColor = UIColor.purpleColor()
    }
    else
    {
        cell.backgroundColor = UIColor.orangeColor()
    }

    if (contains(disabledRows, indexPath.row)) {
        cell.userInteractionEnabled = false
    }
    else {
        cell.userInteractionEnabled = true
    }

    let quest = arrayOfQuestions[indexPath.row]
    cell.setCell(type.Grocery, optionno1:type.option1, optionno2:type.option2)

    cell.mainText.text = type.Grocery


    cell.optionOne.backgroundColor = UIColor.redColor()

    return cell

}

Solution

  • In cellForRowAtIndexPath: method.

    if (indexPath.row == yourDataSourceArray.count - 1) {
    // enable cell
    } else {
    // disable cell
    }