2012-01-31 8 views
11

크기가 다른 이미지가있는 셀에 ReusableCell을 사용하려고합니다. 이미지는 배율이 UIViewContentModeScaleAspectFit 인 220x150 블랙 박스에 넣습니다.다른 크기의 이미지가있는 UITableViewCell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"NewsTableViewCell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 

    NewsItem *item = [self.fetchedResultsController objectAtIndexPath:indexPath]; 

    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:item.imageUrl]]; 
    [cell.imageView setImage:[[UIImage alloc] initWithData:data]]; 
    [cell.imageView setBackgroundColor:[UIColor blackColor]]; 
    [cell.imageView setContentMode:UIViewContentModeScaleAspectFit]; 

    CGRect imageViewFrame = cell.imageView.frame; 
    imageViewFrame.size.width = 220; 
    imageViewFrame.size.height = 150 
    [cell.imageView setFrame:imageViewFrame]; 

    [cell.textLabel setText:item.title]; 

    return cell; 
} 

위의 코드는 다음과 같은 레이아웃을 나타내며 테이블보기에서 스크롤 할 때 이미지가 변경되는 경우가 있습니다. 대신이 구조화되지 않은 레이아웃의

UITableView with images

, 내가하고 싶은 이미지는 다음과 같이 정렬합니다 :

Images in a black box

은 무엇 나는이 ReusableCell으로 잘못하고 있는가?

EDIT1 :

나는 이미지 뷰를 만들고 cell.contentView에 수퍼로이 이미지 뷰를 추가하기 위해 노력하고있어. 다음에

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"NewsTableViewCell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 

    NewsItem *item = [self.fetchedResultsController objectAtIndexPath:indexPath]; 

    UIImage *placeholderImage = [UIImage imageNamed:@"ImagePlaceholderThumb"]; //220x150 

    UIImageView *imageView = [[UIImageView alloc] initWithImage:placeholderImage]; 

    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:item.imageUrl]]; 
    [imageView setImage:[[UIImage alloc] initWithData:data]]; 
    [imageView setBackgroundColor:[UIColor blackColor]]; 
    [imageView setContentMode:UIViewContentModeScaleAspectFit]; 

    CGRect imageViewFrame = imageView.frame; 
    imageViewFrame.size.width = placeholderImage.size.width; 
    imageViewFrame.size.height = placeholderImage.size.height; 
    [imageView setFrame:imageViewFrame]; 

    [cell.contentView addSubview:imageView]; 

    [cell.textLabel setText:item.title]; 

    return cell; 
} 

상기 코드 결과

UIImageView in superview

이는 이미지의 일부처럼, 두 세포에서 볼 수있다. 그들은 내가 설정 한 크기를 유지하지 않는 것 같습니다 imageViewFrame. 왜 그런지 알아?

+0

당신이 찾고있는 무엇이 당신이 그것을하면 않는 한 UIKit는 당신을 위해하지 않을 무언가 인 편지 복싱 및 AFAIK에게 불린다. – Till

+0

그럼 어떻게 할 수 있습니까? – dhrm

+0

내 대답에 대한 의견보기. 또한, 제쳐두고, UIImageView를 만들고 데이터를로드하는 방법이 셀이 화면에서 볼 수있게 될 때마다 발생합니다. 스케치 스크롤을 볼 수 있습니다. 0) 이미지 데이터를 비동기 적으로로드하고 EGOImageView와 같은 캐시를 사용합니다. 1) 일반적으로 셀을 만들 때 셀의 하위 뷰를 만들려고합니다. 셀을 만들 때 하위 뷰의 내용을 변경하려는 경우// 셀 구성 ... – Keller

답변

18

빠른 수정은 콘텐츠 모드 UIViewContentModeScaleAspectFill을 사용합니다. 이미지는 전체 이미지 뷰 범위를 채우기 위해 하나 또는 두 가지 차원으로 늘어납니다.

실제로이 작업을 수행하려면 서브 클래스를 UITableViewCell해야합니다.

THRE는 게으른 솔루션은 새로운 UIImageView를 추가하고 켈러 (이 그냥 누락 된 코드는 그의 대답을 받아 주시기 바랍니다) 그의 대답에 말했듯, 스페이서를 사용하고 있습니다. tableView:cellForRowAtIndexPath:

추출 :

... 
cell.textLabel.text = [NSString stringWithFormat:@"Cell #%i", indexPath.row]; 
cell.imageView.image = [UIImage imageNamed:@"spacer.png"]; /* spacer is 64 x 44 */ 
/* image view width should be ~ 64 px, otherwise it will overlap the text */ 
UIImageView *iv = [[UIImageView alloc] initWithFrame:(CGRect){.size={64, tableView.rowHeight}}]; 
switch (indexPath.row) { 
    case 0: 
     iv.image = [UIImage imageNamed:@"waterfall.png"]; 
     break; 
    /* etc... */ 
} 
if (indexPath.row < 3) { 
    /* add black bg to cell w/ images */ 
    iv.backgroundColor = [UIColor blackColor]; 
} 
iv.contentMode = UIViewContentModeScaleAspectFit; 
[cell.contentView addSubview:iv]; 
... 

표는 다음과 같이 표시됩니다 aspect fit

당신은 기존의 세포 이미지보기에서 자리 표시 자 (위 spacer.png)를 설정해야합니다. 텍스트 레이블을 오른쪽으로 밀어 넣습니다.

당신은 채울 측면을 사용하여 배경 색상 비트 제거 할 수 있습니다 이미지가 경계 outsite 그려 때문에

iv.contentMode = UIViewContentModeScaleAspectFill; 

표는 잘못된 모양을 : 그냥 경계에

aspect fill without clipping

클립 더 나은 결과를 얻으려면 :

iv.clipsToBounds = YES; 

aspect fill

+0

죄송합니다,하지만 지금은 나를위한 해결책입니다. 나는 그들의 비율을 지키기 위해 이미지가 필요합니다. – dhrm

+0

비율을 유지하면 전체 이미지 만 표시되지 않습니다. 어쨌든, 내가 말했던 것처럼 쉽지는 않습니다. 업데이트 된 답변보기 – djromero

2

각 셀 및 contentView에 대한 UIImageView 하위보기를 만듭니다. 각 UIImageView에는 일관된 프레임이 있지만 옵션이 UIViewContentModeScaleAspectFit 인 이미지가 포함되어 있습니다. 그런 다음 UIImageView의 배경색을 검정색으로 설정하십시오.

방금 ​​확인했으나 자리 표시 자 스페이서 이미지를 만들어야 textLabel이 빠져 나갈 수 있습니다. 그냥 문자 복싱으로 이미지의 크기를 동일하게 만드십시오.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 

    //spacer 
    cell.imageView.image = [UIImage imageNamed:@"placeholder"]; 

    //imageview 
    UIImageView *thumbnail = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 80, 44)]; 
    thumbnail.tag = kThumbTag; 
    thumbnail.backgroundColor = [UIColor blackColor]; 
    thumbnail.contentMode = UIViewContentModeScaleAspectFit; 
    [cell.contentView addSubview:thumbnail]; 
    } 

    // Configure the cell... 

    cell.textLabel.text = [NSString stringWithFormat:@"Cell %d", indexPath.row]; 

    cell.imageView.frame = CGRectMake(0, 0, 80, 44); 

    UIImageView *thumb = (UIImageView*)[cell.contentView viewWithTag:kThumbTag]; 
    if (indexPath.row == 0) { 
    [thumb setImage:[UIImage imageNamed:@"image1.png"]]; 
    } else { 
    [thumb setImage:[UIImage imageNamed:@"image2.png"]]; 
    } 

    return cell; 
} 

물론,이 예제는 이미지 (나는 당신이 URL에서 그들을로드 된 몰랐)로드 게으른 없습니다. 이를 위해 서브 클래스를 EGOImageView 또는 비슷한 것으로 사용합니다.

+0

솔루션을 제공해 주셔서 감사합니다. 제 EDIT1을 한번보세요. – dhrm

+0

자리 표시 자 이미지의 프레임 크기가 220x150입니다. 150px는 실제로 셀 높이가 맞습니까? 그렇다면 cell.rowHeight (너비 또는 viewDidLoad)를 설정하면됩니다. 그렇지 않으면 자리 표시 자 이미지가 원하는 프레임 크기인지 확인하고 프레임의 크기를 조정하십시오. – Keller

+0

사실, UITableView 대리자 메서드 'indentationLevelForRowAtIndexPath'를 사용할 수도 있습니다. – Keller

관련 문제