2013-11-25 3 views
8

"sizeWithFont"를 사용 거기에 많은 솔루션 또는 여기계산 셀 높이 7

아이폰 OS 7 추천되지 할 일이 비슷한이있다 내가 함께 재현 한 몇 가지 코드되어 있습니다 지금까지. 높이가 변경되지만 전혀 정확하게 : 또 다른 예를 들어

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

// Configure the cell... 
cell.textLabel.text = "The Cell's Text!"; 
cell.textLabel.numberOfLines = 0; 
[cell.textLabel setLineBreakMode:NSLineBreakByWordWrapping]; 
[cell.textLabel sizeToFit]; 

return cell; 
} 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; 
{ 
CGRect screenBounds = [[UIScreen mainScreen] bounds]; 
CGSize screenSize = screenBounds.size; 

NSAttributedString *aString = [[NSAttributedString alloc] initWithString:"The Cell's Text!"]; 
UITextView *calculationView = [[UITextView alloc] init]; 
[calculationView setAttributedText:aString]; 
CGSize size = [calculationView sizeThatFits:CGSizeMake(screenSize.width, FLT_MAX)]; 
return size.height; 
} 

, 여기에 유사한 대답 : https://stackoverflow.com/a/9828777/693121를 내가 전에 말했듯이,이되지 않는 코드를 사용하지만.

답변

-1

문자열의 크기를 얻으려면 - (CGSize)sizeWithAttributes:(NSDictionary *)attars을 사용해야합니다.

은 그래서 예를 들어, 당신은 같은 텍스트 레이블의 높이를 계산합니다 :

CGSize *cellSize = [cell.textLabel.text sizeWithAttributes:@{NSFontAttributeName:[cell.textLabel.font]}]; 

또는

CGSize *rowSize = [aString sizeWithAttributes:nil]; 
당신은 이전을 대체 할 문서에 언급 된 것 방법을 사용한다
+3

. Apple의 docs에서 : "한 줄에 지정된 글꼴로 렌더링 할 문자열의 크기를 반환합니다." 다중 행 레이블을 기반으로 셀 높이를 변경하려는 경우 유용하지 않습니다. – rdelmar

14

- boundingRectWithSize : 옵션 : 속성 : 컨텍스트 :. 다음은 작동해야한다고 생각하는 예제입니다 (어쨌든 여러 줄 레이블과 함께 작동 함).

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSStringDrawingContext *ctx = [NSStringDrawingContext new]; 
    NSAttributedString *aString = [[NSAttributedString alloc] initWithString:@"The Cell's Text!"]; 
    UITextView *calculationView = [[UITextView alloc] init]; 
    [calculationView setAttributedText:aString]; 
    CGRect textRect = [calculationView.text boundingRectWithSize:self.view.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:calculationView.font} context:ctx]; 
     return textRect.size.height; 
    } 

여기서는 텍스트보기를 self.view의 크기로 설정한다고 가정합니다. 그렇지 않다면 텍스트보기에 initWithFrame을 사용하고 boundingRectWithSize : 매개 변수에 대해 calculationView.frame.size를 전달해야합니다.

+0

어떤 이유인지 항상 13.8의 높이를 반환합니까? "aString"변수의 텍스트 양에 관계없이 – Demasterpl

+1

@Demasterpl, 죄송합니다, 내 대답에 잘못된 옵션 매개 변수를 사용했지만 NSStringDrawingUsesLineFragmentOrigin이어야합니다. 내 대답을 바로 잡았어. – rdelmar

+0

높이가 큰 숫자 일지라도 때때로 기본 높이를 유지하는 것처럼 보일지라도 꽤 훌륭한 값을 반환하는 것처럼 보입니다. 또한 셀 속성 (예 : sizeToFit 및 setLineBreakMode)을 제거해도 차이가없는 것처럼 보입니다. : – Demasterpl

6

여기이 가장 쉬운 버전, 아이폰 OS 7 않습니다 (단 자동 레이아웃 기반 uitableviewcells에 대한) 모든 무거운 다음 자동 레이아웃 제약 조건을 재 - 평가 및 휴대를위한 완벽한 높이를 반환

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: @"Cell"]; 

    [self configureCell:cell]; 

    // edit: Need to call [cell layoutIfNeeded]; otherwise the layout changes wont be applied to the cell 

    [cell layoutIfNeeded]; 


    return [cell.contentView systemLayoutSizeFittingSize: UILayoutFittingCompressedSize].height; 
} 

systemLayoutSizeFittingSize. 진정해?

+0

[self configureCell : cell] 메서드는 무엇을합니까? ? – MiQUEL

+0

데이터 개체 (예 : 레이블 설정)에 종속 된 셀의 기본 설정. 콘텐츠가있는 셀을 채우면 자동 레이아웃에서 필요한 높이를 자동으로 결정할 수 있습니다. – Wirsing

+1

이것이 너무 비효율적인지 궁금합니다. –

2

내 동료 (사진 제공 : Anirudh)와 잘 작동 그것을 가지고, 도움이 될 수 있습니다 :이 작동하지 않습니다

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

//Calculating height on base of length of text 
    UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody]; 
    NSAttributedString *attributedText = 
    [[NSAttributedString alloc] 
    initWithString:YOURSTRING //[NSString string withformat:@"\n Yourstring"] \n for: number of lines require for static label in cell 
    attributes:@ 
    { 
    NSFontAttributeName: font 
    }]; 
    CGRect rect = [attributedText boundingRectWithSize:(CGSize){CELL_CONTENT_WIDTH, CGFLOAT_MAX} 
               options:NSStringDrawingUsesLineFragmentOrigin 
               context:nil]; 
    CGSize size = rect.size; 

    // NSString *height = [NSString stringWithFormat: @"%.2f", ceilf(size.height)+22]; 
    return (ceilf(size.height)+22)*0.6; //change 0.6 to 0.9 according to the difference in required and extra calculted height, it works for me every time 
} 
0
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSString *yourText = [[resultArray objectAtIndex:indexPath.row] valueForKey:@"review_text"]; 
    CGSize lblwidth = CGSizeMake(300, CGFLOAT_MAX); 
    CGSize requiredSize = [yourText sizeWithFont:[UIFont fontWithName:@"CALIBRI" size:17] constrainedToSize:lblwidth lineBreakMode:NSLineBreakByWordWrapping]; 
    int calculatedHeight = requiredSize.height+50; 
    return (float)calculatedHeight; 
}