Search code examples
objective-cios6celltextlabelaccessorytype

Objective-c set cell accessorytype based on cell text? iOS SDK


I have a dynamic table view with 2 section, and 4 rows in each which are populated by arrays.

Only one cell should be checked, at the moment none are. I know the text for the cell I want checked.

So my question is, can I set the accessoryType for a cell based on the text that cell contains?

Like IF cell.textLabel.text equals THIS then set that cell accessoryType check.

Edit

The code I have so far, taking into account comments below is this:

  switch (indexPath.section) {
        case standardSection:
            serverLoc.textLabel.text = [self.serverSelection objectAtIndex:indexPath.row];
            if ([[self.serverSelection objectAtIndex:indexPath.row] rangeOfString:cellValue].location != NSNotFound) {
                serverLoc.accessoryType = UITableViewCellAccessoryCheckmark;
            }
            break;
        case qualitySection:
            serverLoc.textLabel.text = [self.qServerSelection objectAtIndex:indexPath.row];
            if ([[self.qServerSelection objectAtIndex:indexPath.row] rangeOfString:cellValue].location != NSNotFound) {
                serverLoc.accessoryType = UITableViewCellAccessoryCheckmark;
            }
            break;
        default:
            break;
    }

The sections set them selves up like this:

Section 1:

Chicago, IL London, UK San Jose, CA Washington, DC

Section 2:

Chicago, IL (Q) London, UK (Q) San Jose, CA (Q) Washington, DC (Q)

As you can see I'm checking against the value of CellValue. CellValue is set using a delegate from the previous view.

Let's say this time is equals London, UK. When I come into this view both London, UK and London, UK (Q) are checked, I only want the one without (Q) checked. Even using "isEqualToString" this occurred. If cellValue equals London, UK (Q) then this works.


Solution

  • Do this in cellForRowAtIndexPath. After you have created your cell just do a check on the value in the array (assuming the array contains NSStrings). So:

    if ([[self.myArray objectAtIndex:indexPath.row] isEqualToString:@"the string I want"]) {
         cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    

    Edit: Based on your comment all strings will start with the same thing but may have differences. You could do something like this:

    if ([[self.myArray objectAtIndex:indexPath.row] rangeOfString:@"London,"].location != NSNotFound) {
         cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    

    This would say if the NSString contains "London," then evaluate to YES. Or in other words, the NSString contains "London,"