Desmond
Desmond

Reputation: 5001

How to Select & checkmark the row after load in UITableview

I have a selection that will select just 1 row of category. but I will like it to select Spirits row when loaded.

Something like this:

enter image description here

At the moment it comes to this without selecting anything:

enter image description here

Where shall I do the compare for the in order for it to selectRowAtIndexPath?

// Customize the appearance of table view cells.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }


    categoryString = [arrayCategory objectAtIndex:indexPath.row];
    cell.textLabel.text = categoryString;
    if (cell.textLabel.text == categoryString) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;

    }

    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell* newCell = [tableView cellForRowAtIndexPath:indexPath];
    int newRow = [indexPath row];
    int oldRow = (lastIndexPath != nil) ? [lastIndexPath row] : -1;

    if(newRow != oldRow)
    {
        newCell.accessoryType = UITableViewCellAccessoryCheckmark;
        newCell.highlighted =YES;
        UITableViewCell* oldCell = [tableView cellForRowAtIndexPath:lastIndexPath];
        oldCell.accessoryType = UITableViewCellAccessoryNone;
        lastIndexPath = indexPath;
        oldCell.highlighted = NO;

    }
    [tableView deselectRowAtIndexPath:(NSIndexPath *)indexPath animated:YES];
}

Upvotes: 0

Views: 3190

Answers (2)

EmptyStack
EmptyStack

Reputation: 51374

Use selectRowAtIndexPath:animated:scrollPosition: method to select a row programatically.

Few things to correct in your code. You should use isEqualToString: method to match the strings, like this, if ([cell.textLabel.text isEqualToString:categoryString]) {. Next thing is, you are assigning the categoryString to cell.textLabel.text, and on the next line you are matching them, so it would always return YES. I think you are matching the wrong values.

Upvotes: 1

alloc_iNit
alloc_iNit

Reputation: 5183

You have to manually set multiple check marks. for that you can use UIImageview for each UITableViewCell and as per the stored old data, you have to set check marks in didSelectRowAtIndexPath(delegate method of UITableView).

Upvotes: 0

Related Questions