2014-04-21 3 views
0

나는 이것이 어리석은 단순한 질문이 될 것이라는 것을 알고 있지만 나는 원으로 돌아가고있다.텍스트에 필요한 숫자 줄을 계산하는 방법

필자는 uitableview에 표시하려는 여러 문자열을 가지고 있습니다. 이 문자열 중 일부는 매우 길다. 나는 문자열을 표시하기 위해 jQuery과에 필요한 행의 수를 얻을 수있는 방법

- (CGFloat)cellHeightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSString *cellString = <YOUR MODEL OBJECT>; 

    NSDictionary *attributes = @{ NSFontAttributeName : [UIFont systemFontOfSize:16.0f] }; 
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] 
               initWithString: cellString 
               attributes:attributes]; 

    CGFloat width = self.tableView.frame.size.width - 32.0f; 

    CGRect frame = [attributedString boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil]; 

    // Add some extra padding to the height  
    CGFloat height = frame.size.height + 16.0f; 

    return ceil(height); 
} 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return [self cellHeightForRowAtIndexPath:indexPath]; 
} 

: 나는 이전에 다음과 같은 대답을 셀 높이를 계산하고 선택하는 방법을 요청했습니다.

+0

에 해당합니다. 실제로 줄 수 또는 텍스트의 전체 높이를 원하십니까? – Rich

+0

목표가 적절한 numberOfLines 속성을 설정하는 것이라면 0으로 설정하면 자동으로 크기가 조정됩니다. 그 경우가 아니라면, 레이블의 lineHeight에 대한 텍스트 높이를 나눌 수 있습니다. – andreamazz

+0

@andreamazz 단락 스타일을 변경 한 경우가 아니라면 'NSAttributedString'을 사용하고 있기 때문에 더 이상 작동하지 않습니다. – Rich

답변

0

실제로 셀 높이를 계산하는 가장 좋은 방법은 높이 계산에 프로토 타입 셀을 사용하는 것입니다.

사용자 인터페이스 확장에 property을 추가

@interface TableViewController() 

@property (nonatomic, strong) TableViewCell *prototypeCell; 

@end 

을 다음 유유히로드 : 이제

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellId" forIndexPath:indexPath]; 

    [self configureCell:cell forRowAtIndexPath:indexPath]; 

    return cell; 
} 

-(void)configureCell:(TableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Set up you cell from your model 
} 

:

- (TableViewCell *)prototypeCell 
{ 
    if (!_prototypeCell) 
    { 
    _prototypeCell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Prototype"]; 
    } 
    return _prototypeCell; 
} 

-[configureCell:forRowAtIndexPath:] 형식 패턴을 사용하도록 -[tableView:cellForRowAtIndexPath:] 방법 변경 이 방법을 사용하여 프로토 타입을 설정 한 다음, h 그 중 8 개는 -[tableView:heightForRowAtIndexPath:] :

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    [self configureCell:self.prototypeCell forRowAtIndexPath:indexPath]; 
    [self.prototypeCell layoutIfNeeded]; 

    CGSize size = [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; 
    return ceil(size.height); 
} 
관련 문제