2013-04-10 179 views
7

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

这里是我的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或similiar程序在同一时间停留,而图像的图像内容。但是这种方法会花费很多时间,我想应该有更简单的方法来做到这一点。

回答

15

没有子:

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

将'.5'改成正确的比例f或者你的情况

+7

这是一个聪明的主意!顺便说一下,右侧表达式可以进一步简化为'CGAffineTransformMakeScale(0.5,0.5)'。 – Pang 2015-12-14 05:45:08

+2

不适用于我。 – 2016-10-04 07:34:23

9

这里的最佳解决方案是创建自己的单元格,添加图像,标签contentView,并调整它们的方式。

但也有另一种方式,又需要从UITableViewCell创建一个子类,并覆盖layoutSubviews选择:

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

不幸的是,这似乎导致我的文字覆盖的图像。 – Sam 2013-12-12 16:15:03

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

这似乎很有创意,但不幸的是它不适合我。任何想法? – umair151 2016-05-04 06:30:41

+0

@ umair151虽然我使用'.offsetInPlace(dx:dy:)'而不是直接操作'.origin'和'.size'属性,它对我很有用 – Alnitak 2016-07-01 15:54:36

+0

对于那些想知道的,'offsetInPlace'等价于'CGRectOffset'。 – 2016-10-04 07:28:07

0

更新的swift3

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