更改表格视图单元格中图像按钮的位置

时间:2012-11-05 12:11:16

标签: iphone ios uitableview uibutton

我有一个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];

2 个答案:

答案 0 :(得分:0)

UITableViewCell的默认布局为[imageView] [textLabel] [accessoryView]。你无法改变它。

如果您想在UITableViewCell中随意定位图片,则必须在单元格UIImageView中添加contentView

答案 1 :(得分:0)

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

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

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

- (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;
}
相关问题