I am converting an iPhone application to an iPad and I am stuck in an innocent and seemingly trivial positioning problem. I have a UITableViewCell that only contains a UISwitch centered in the cell. The cell is in a UITableView with a Grouped style.
On iPhone, I just set the center of the switch property to the center of the cell in tableView:cellForRowAtIndexPath: This is enough for the iPhone, because the center of the cell is the same, regardless of the style of the table. This also happens on the iPhone, but the offset is smaller, so the difference is more subtle. Here is the code for the iPhone:
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; UISwitch *view = [[UISwitch alloc] initWithFrame:CGRectZero]; [view addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged]; view.center = cell.center; cell.selectionStyle = UITableViewCellSelectionStyleNone; [cell.contentView addSubview:view]; [view release];
On the iPad, without changing any code, the switch position is still in the center of the iPhone screen. This is bad, since the iPad is much larger than the iPhone. So I moved the positioning code to tableView:willDisplayCell:forRowAtIndexPath: and now on the other side of the center (closer to the right side of the screen).
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { UISwitch *s = (UISwitch *)[cell.contentView viewWithTag:SwitchTag]; s.center = CGPointMake(cell.contentView.center.x,s.center.y);
}
And yet, when I register the various coordinates and frames that interest me, I get what I expect: the x coordinate of the center of the cell is 384.0, which is half the width of the screen. I also tried recounting the entire UISwitch frame, but since I am using screen values, the switch ends in the same place, too far to the right.
I think some conversion happens after tableView:willDisplayCell:forRowAtIndexPath: is called (or before, even) to make all these numbers pointless. It seems that the whole cell is shifted by x, where x is the distance from the edge of the screen to the beginning of the cell, even if it is not specified in the frame property.
I am sure there is something trivial that I am missing. Please enlighten me.