UITableViewCell imageView内边距

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个回答

17

不需要子类化:

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

将'.5'更换为适合您情况的正确比例


7
聪明的主意!顺便提一下,右边的表达式可以进一步简化为 CGAffineTransformMakeScale(0.5, 0.5) - Pang
3
嗨,我来自未来,它不起作用 :) - Itai Spector

9

这里最好的解决方案是创建自己的单元格,在contentView中添加图像和标签,并根据需要进行微调。

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

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.imageView.frame = CGRectMake(10, 10, 50, 50);
    self.imageView.contentMode = UIViewContentModeCenter;
}

2
不幸的是,这似乎导致我的文本被图像覆盖。 - Sam

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

那看起来很有创意,但不幸的是对我没用。你有什么想法吗? - umair151
@umair151,这对我有效,尽管我使用的是.offsetInPlace(dx:dy:)而不是直接操作.origin.size属性。 - Alnitak
对于那些想知道的人,offsetInPlace 相当于 CGRectOffset - Iulian Onofrei

1

更新为Swift 3版本

cell?.imageView?.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接