0

I have a custom cell in my UITableView that contains a button. This button acts as a check box and has it's own class that swaps between two images. Anyway...What I'm trying to do is set the check box state to "checked" for certain cells containing a certain attribute. This code below gives me the expected result, but I do not want to hard-code these values with if-statements. I would like to instead loop though my array of "currentItemCondiment" to get the same result.

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

    var cell: customCell! = tableView.dequeueReusableCellWithIdentifier("ItemCell" ,forIndexPath: indexPath) as customCell

    let menuItem = self.condiments[indexPath.row]

    if (currentItemCondiments[0] == menuItem.title) {
        cell.customCellCheckbox.setSelected()
    }
    else if (currentItemCondiments[1] == menuItem.title) {
        cell.customCellCheckbox.setSelected()
    }

    else {
        cell.customCellCheckbox.setUnSelected() 
    }
    return cell
}

I want to write a loop like the one below here to get the same result as above, but this code will only select the checked box at its last index.

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

    var cell: customCell! = tableView.dequeueReusableCellWithIdentifier("ItemCell" ,forIndexPath: indexPath) as customCell

    let menuItem = self.condiments[indexPath.row]

    for item in currentItemCondiments {
        if (item == menuItem.title) {
            cell.customCellCheckbox.setSelected()
        }
        else {
            cell.customCellCheckbox.setUnSelected()
        }

    return cell
}

Any help would be much appreciated, Thanks.

1 Answer 1

1

Add 'break' when checkbox is selected.

for item in currentItemCondiments {
    if (item == menuItem.title) {
        cell.customCellCheckbox.setSelected()
        break
    }
    else {
        cell.customCellCheckbox.setUnSelected()
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant! I wish I had the reputation to up-vote this...Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.