2013-04-10 124 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)