I’m a bit stumbled here. The UIButton positions itself nicely the first time it’s loaded. But every subsequent call to -tableView:cellForRowAtIndexPath: seems to manipulate the UIButton´s frame making it smaller. It seems to add to the frame.origin.x and it seems to subtract from the frame.size.width. The UIButton is first setup in -viewDidLoad like this:
self.facebookButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.facebookButton setFrame:CGRectMake(0, 0, 159, 29)];
[self.facebookButton setBackgroundImage:[UIImage imageNamed:@"LoginWithFacebookNormal.png"] forState:UIControlStateNormal];
[self.facebookButton setBackgroundImage:[UIImage imageNamed:@"LoginWithFacebookPressed.png"] forState:UIControlStateHighlighted];
[self.facebookButton addTarget:self action:@selector(loginToFacebook) forControlEvents:UIControlEventTouchUpInside];
My cellForRowAtIndexPath looks like this (I’m not reusing cells since I’m only displaying one cell):
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:nil];
// Set the background view of the cell to be transparent
UIView *backView = [[UIView alloc] initWithFrame:CGRectZero];
backView.backgroundColor = [UIColor clearColor];
cell.backgroundView = backView;
[self.facebookButton setCenter:cell.center];
// Magic code that puts the button IN the center of the cell
self.facebookButton.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
[cell.contentView addSubview:self.facebookButton];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
I see several issues:
You’re setting the button’s center to the cell’s center, which is completely incorrect. The cell’s center is in the coordinate system of its superview, but your button’s center is in the coordinate system of the contentView. You should probably use something like
cell.center = CGPointMake(CGRectMidX(cell.contentView.bounds), CGRectMidY(cell.contentView.bounds)), and even there you’re going to have issues with fractional origins depending on the size of the button and of the contentView.You’re trying to set up the button partially in this method, but not fully. You should re-set its frame here
You have the autoresizing mask set up to actually shrink (or grow) the button based on how the contentView moves. This means that if, for example, the table goes into edit mode and the delete button appears, your button is going to shrink. It also means that if you have a grouped table, the button is going to shrink in between
-cellForRowAtIndexPath:and the actual display of the table (because the cell itself shrinks to accommodate the padding in grouped tables`