2009-07-15 3 views
19

UITableView 을 사용하고 UITableViewCellStyleSubtitle을 사용하여 만든 셀을 사용합니다. 모든 셀의 높이는레이블이 UITableViewCell에서 정렬됩니다.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 

대리자 메서드를 사용하여 동적으로 조정됩니다.

당신이 사진

에 볼 수있는 문제 ( 참고 : 이미지 업데이트) 셀의 상단에 textLabel라는 및 detailTextLabel의 정렬을 설정하는 방법에

http://img.skitch.com/20090715-g7srxgee2d7fhi5rab2wufrdgm.png

? 당신이 당신의 세포 크기를 조정하고 그러나 고맙습니다

+0

자막 텍스트가 셀의 맨 아래로 흐르고 다음으로 보입니다.이게 내가 본 것입니까? 또한,이 장치 또는 시뮬레이터에서 발생합니까? – jbrennan

+0

heightForRowAtIndexPath 구현을 게시 할 수 있습니까? –

+4

스크린 샷을 멋지게 터치하십시오. –

답변

8

여기에 셀을 서브 클래 싱하지 않는 또 다른 솔루션이 있으므로 다른 테이블 스타일에서도 확실히 작동합니다. (다른 솔루션을 확인하지 않았습니다.) 제목 및 세부 문자열은 내 UITableViewController 헤더에 선언되어 이미 정의되어 있습니다. 그것들은 매우 길지는 않지만, 확실히 높이 4000 안에 있습니다!

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    CGRect frame = [UIScreen mainScreen].bounds; 
    CGFloat width = frame.size.width; 

    int section = indexPath.section; 
    int row = indexPath.row; 

    NSString *title_string = [title_strings_array objectAtIndex:row]; 
    NSString *detail_string = [detail_strings_array objectAtIndex:row]; 

    CGSize title_size = {0, 0}; 
    CGSize detail_size = {0, 0}; 

    if (title_string && [title_string isEqualToString:@""] == NO) { 
     title_size = [title_string sizeWithFont:[UIFont systemFontOfSize:22.0] 
           constrainedToSize:CGSizeMake(width, 4000) 
            lineBreakMode:UILineBreakModeWordWrap]; 
    } 

    if (detail_string && [title_string isEqualToString:@""] == NO) { 
     detail_size = [detail_string sizeWithFont:[UIFont systemFontOfSize:18.0] 
           constrainedToSize:CGSizeMake(width, 4000) 
            lineBreakMode:UILineBreakModeWordWrap]; 
    } 

    CGFloat title_height = title_size.height; 
    CGFloat detail_height = detail_size.height; 

    CGFloat content_size = title_height + detail_height; 

    CGFloat height; 

    switch (section) { 

     case 0: 
      height = content_size; 
      break; 

     //Just in case 
     default: 
      height = 44.0; 
      break; 

    } 

    return height; 

} 
1

, 당신은있는 NSString의 다양한 크기 조정 방법과 그것을해야 (난 정말있는 UITableViewCell 및 최우선 layoutSubviews을 서브 클래스에 의해 그것을 할 못해하지 않음). 그렇게하면 셀을 만드는 방법과 공백을 피하는 방법을 정확하게 결정할 수 있습니다.

36

글쎄, 이건 오후에 들었지만, 알아 냈다고 생각해. 내가 알 수있는 한, 이것은 UITableViewCell이 textLabel 및 detailTextLabel을 레이아웃하는 방법에 버그가있는 것으로 보입니다. 행 높이를 설정하면 두 레이블에 같은 높이를 할당하는 것처럼 보입니다. 즉, detailTextLabel에 더 많은 공간이 필요하지만 위에서 보았던 동작을 정확히 수행한다는 의미입니다. 이 문제를 해결하기 위해 내가 한 두 가지는 다음과 같습니다. 그것을 해결하기 위해 UITableViewCell을 하위 클래스에 추가해야했지만 최소한의 코드가 필요했습니다.

먼저 각 행의 높이를 올바르게 계산했는지 확인하십시오. 이 메서드를 테이블 뷰 대리자에 넣습니다. 자신과 글꼴 방법을 바꾸기 :

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSString *cellDetailText = [[self itemForIndexPath: indexPath] detailDescription]; 
    NSString *cellText = [[self itemForIndexPath: indexPath] description]; 
    // The width subtracted from the tableView frame depends on: 
    // 40.0 for detail accessory 
    // Width of icon image 
    // Editing width 
    // I don't think you can count on the cell being properly laid out here, so you've 
    // got to hard code it based on the state of the table. 
    CGSize constraintSize = CGSizeMake(tableView.frame.size.width - 40.0 - 50.0, CGFLOAT_MAX); 
    CGSize labelSize = [cellText sizeWithFont: [self cellTextLabelFont] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap]; 
    CGSize detailSize = [cellDetailText sizeWithFont: [self cellDetailTextLabelFont] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap]; 

    CGFloat result = MAX(44.0, labelSize.height + detailSize.height + 12.0); 
    return result; 
} 

그런 다음, 서브 클래스있는 UITableViewCell 및 오버라이드 (override) layoutSubviews :

#import "UITableViewCellFixed.h" 


@implementation UITableViewCellFixed 
- (void) layoutSubviews { 
    [super layoutSubviews]; 
    self.textLabel.frame = CGRectMake(self.textLabel.frame.origin.x, 
             4.0, 
             self.textLabel.frame.size.width, 
             self.textLabel.frame.size.height); 
    self.detailTextLabel.frame = CGRectMake(self.detailTextLabel.frame.origin.x, 
              8.0 + self.textLabel.frame.size.height, 
              self.detailTextLabel.frame.size.width, 
              self.detailTextLabel.frame.size.height); 
} 
@end 
+1

훌륭한 답변은 완벽하게 작동했습니다. 좋은 터치 : detailTextLabel.text == nil 인 경우 4.0을 12.0으로 대체하여 셀의 detailText가 없을 때 뷰에서 textLabel을 세로 가운데에 배치합니다. –

+0

그것은 매력과 같은 woks입니다! – wal

+0

이것은 정말 유용한 트릭입니다. 감사! –

-2

는 textLabel라는 및 detailTextLabel 자동 크기 마스크를 사용하여 배치되어 있다고 밝혀지면, 어쩌면 당신은 할 수있다 셀을 반환하면 다음과 같이 처리됩니다.

cell.textLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin; 
cell.detailTextLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; 

이 방법이 작동하는 경우 셀을 서브 클래 싱하는 것보다 쉽습니다. 나는 그것을 시도하지 않았다.

+0

물론 쉽지만 일을하지는 않습니다. layoutSubviews-overriding이 올바른 방법입니다. – slatvick

관련 문제