Objective-C - cellForRowAtIndexPath导致按钮框改变大小?

时间:2012-03-10 21:49:24

标签: objective-c ios cocoa-touch uitableview

我在这里有点磕磕绊绊。 UIButton在第一次加载时很好地定位。但是,对-tableView:cellForRowAtIndexPath:的所有后续调用似乎都会操纵UIButton的框架,使其变小。它似乎添加到frame.origin.x,似乎从frame.size.width中减去。首先在-viewDidLoad中设置UIButton,如下所示:

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];

我的cellForRowAtIndexPath看起来像这样(我没有重复使用单元格,因为我只显示一个单元格):

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;

1 个答案:

答案 0 :(得分:1)

我看到几个问题:

  1. 您将按钮的中心设置为单元格的中心,这完全不正确。单元格的中心位于其超视图的坐标系中,但是按钮的中心位于contentView的坐标系中。您可能应该使用类似cell.center = CGPointMake(CGRectMidX(cell.contentView.bounds), CGRectMidY(cell.contentView.bounds))的内容,即使在那里,您也会遇到分数来源的问题,具体取决于按钮和contentView的大小。

  2. 您尝试在此方法中部分设置按钮,但不完全。你应该在这里重新设置它的框架

  3. 您已设置自动调整大小以根据contentView的移动方式实际缩小(或增大)按钮。这意味着,例如,如果表格进入编辑模式并且出现删除按钮,则按钮将缩小。这也意味着如果你有一个分组表,那么按钮将在-cellForRowAtIndexPath:和表的实际显示之间收缩(因为单元本身缩小以适应分组表中的填充

    < / LI>