How to center text in a UITableViewCell when accessory is UITableViewCellAccessoryCheckmark
There are 2 things you need to do:
First, you need to make sure you set the table style to Default: UITableViewCellStyleDefault
. All other styles use a detailTextLabel
in one way or another and you won't be able to set the textLabel's alignment property.
[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]
Then you can set the alignment of your cell's textLabel:
cell.textLabel.textAlignment = NSTextAlignmentCenter;
Then setting the accessory to checkmark based on whatever your data requires.
cell.accessoryType = ( myDataMatches ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone );
Screenshot
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;
}
There seems to be a much simpler answer (See this answer). In short, you are centering the label in the cell's content view. Instead, center it in the cell itself, then it won't move.
Tried it out, it works on iOS 11.2.