9

我想为 UITableView 单元格 imageView 设置边距或填充,我该怎么做?我heightForRowAtIndexPath只能设置行高。如果我增加它,它只会放大单元格中的图像。

这是我的 cellForRow 方法

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID] autorelease];
        cell.textLabel.numberOfLines = 1;
        cell.textLabel.font = [UIFont systemFontOfSize:kSystemFontSize];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.textLabel.textColor = [UIColor whiteColor];
    }
    cell.textLabel.text = [_dataArray objectAtIndex:indexPath.row];
    cell.imageView.image = [UIImage imageNamed:[_imageArray objectAtIndex:indexPath.row]];
    cell.backgroundColor = [UIColor clearColor];

    return cell;
}

目前我只知道一种方法可以做到这一点 - 使用 Photoshop 或类似程序缩小图像的图像内容,同时保持不变。但是这种方法会花费很多时间,我想应该有更简单的方法来做到这一点。

4

4 回答 4

17

没有子类化:

cell.imageView.transform = CGAffineTransformScale(CGAffineTransformIdentity, .5, .5);

根据您的情况以正确的比例更改“.5”

于 2015-10-28T10:28:46.613 回答
9

这里最好的解决方案是创建您自己的单元格,在其中添加图像、标签contentView并根据需要调整它们。

但是还有另一种方法,您需要再次创建一个子类UITableViewCell并覆盖layoutSubviews选择器:

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.imageView.frame = CGRectMake(10, 10, 50, 50);
    self.imageView.contentMode = UIViewContentModeCenter;
}
于 2013-04-10T11:27:15.817 回答
3

这适用于 iOS 7:

- (void)layoutSubviews
{
    [super layoutSubviews];
    CGRect imageViewFrame = self.imageView.frame;
    imageViewFrame.origin.x = 10;
    imageViewFrame.origin.y += 5;
    imageViewFrame.size.height -= 10;
    imageViewFrame.size.width -= 10;
    self.imageView.frame = imageViewFrame;
}
于 2013-12-17T06:19:14.873 回答
1

为 swift3 更新

cell?.imageView?.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
于 2018-01-25T13:27:33.037 回答