0

UITableView在每个单元格前面都有一个带有图像的按钮,我想调整它的坐标UIButton。写入的相关代码cellForRow如下:

 UIImage *image = [UIImage imageNamed "unchecked.png"];
 UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
 CGRect frame1 = CGRectMake(0.0,0.0, image.size.width, image.size.height);** //changing the coordinates here doesn't have any effect on the position of the image button.
 button.frame = frame1; // match the button's size with the image size 
 [button setBackgroundImage:image forState:UIControlStateNormal]; // set the button's target to this table view controller so we can interpret touch events and map that to a NSIndexSet [button addTarget :self action: @selector(checkButtonTapped:event) forControlEvents:UIControlEventTouchUpInside];
4

2 回答 2

0

设置视图的框架会设置其相对于其超级视图的位置,因此您需要在设置其框架之前使您的按钮成为单元格的子视图。

然而,这不应该在 cellForRowAtIndexPath 中完成,因为这意味着每次表格视图“重用”一个单元格时,您都会分配一个新按钮。您应该创建按钮,并在初始化表格视图单元格时设置其框架,以便每个单元格只创建一个按钮。

所以你想要的是一个 UITableViewCell 子类,它的 init 方法看起来像这样。

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        UIImage *image = [UIImage imageNamed:@"backgroundImage.png"];
        [self addSubview:button];
        [button setFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
    }
    return self;
}
于 2012-11-05T12:53:33.940 回答
0

的默认布局UITableViewCell是 [ imageView][ textLabel][ accessoryView]。你无法改变这一点。

如果您想在您的单元格中任意放置图像,则UITableViewCell必须UIImageView在单元格的contentView.

于 2012-11-05T12:23:47.447 回答