Search code examples
xcodeios5uitableview

How to center text in a UITableViewCell when accessory is UITableViewCellAccessoryCheckmark


I'm trying to keep text centred in a UITableViewCell when I have the accessoryView set to UITableViewCellAccessoryCheckmark. I'm also using a storyboard with this class.

Here's a screenshot of what I don't want.

How do I stop the text from being indented to the left?

enter image description here

My willDisplayCell method..

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == [self cellToCheckmark]) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else {
        NSLog(@"Not Being Checked");
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

cell.textLabel.textAlignment = UITextAlignmentCenter;

    if (cell.shouldIndentWhileEditing == YES) {
        cell.shouldIndentWhileEditing = NO;
    }
}

CellForRowAtIndexPath:

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

    UITableViewCell *cell = nil;

    static NSString *CellIdentifier = @"Cell";
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    cell.textLabel.textAlignment = UITextAlignmentCenter;

    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
                cell.textLabel.text = @"Google";
                break;

            case 1:
                cell.textLabel.text = @"Bing";
                break;

            case 2:
                cell.textLabel.text = @"Yahoo!";
                break;

            default:
                break;
        }
    }

    if (indexPath.row == [self cellToCheckmark]) {
        NSLog(@"Being Checked");
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else {
        NSLog(@"Not Being Checked");
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    if (cell.shouldIndentWhileEditing == YES) {
        cell.shouldIndentWhileEditing = NO;
    }   
    return cell;
}

Solution

  • iOS 8+ solution:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.textLabel.text = ...;
        if (/* your condition */) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            cell.layoutMargins = UIEdgeInsetsMake(0, 40, 0, 10);
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.layoutMargins = UIEdgeInsetsMake(0, 10, 0, 10);
        }
        return cell;
    }