UITableViewCell imageView padding

2020-03-14 03:02发布

I would like to set up margins or paddings for UITableView cells imageView, how could I do that? With heightForRowAtIndexPath I can only set rows height. And it just enlarges the image in cell if I increase it.

Here is my cellForRow method

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

Currently I only know one method how I could do it - shrink the image content of the images using photoshop or similiar program while staying at the same time. But such method would take a lot of time, and I guess there should be easier way to do this.

4条回答
Evening l夕情丶
2楼-- · 2020-03-14 03:15

This works on 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;
}
查看更多
何必那么认真
3楼-- · 2020-03-14 03:23

Without subclassing:

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

change the '.5' with the right proportion for your case

查看更多
唯我独甜
4楼-- · 2020-03-14 03:38

updated for swift3

cell?.imageView?.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
查看更多
我想做一个坏孩纸
5楼-- · 2020-03-14 03:39

The best solution here is to create your own cell, add image, labels inside of contentView and tweak them how you want.

But there's also another way, again you need to create a subclass from UITableViewCell and override layoutSubviews selector:

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.imageView.frame = CGRectMake(10, 10, 50, 50);
    self.imageView.contentMode = UIViewContentModeCenter;
}
查看更多
登录 后发表回答