2015-04-30 53 views
0

UITableview單元格返回的高度與其文本無關。UITableviewCell基於標籤不工作的自動調整大小

我一直在處理一個相當煩人的錯誤,其中xcode返回單元格的不正確高度,一般來說,單元格中元素的返回像素高度非常不一致。

我以爲我可以實施下面的方法來清理東西,但事實證明只是爲了讓事情變得更糟。

在谷歌文檔中的第一個圖像是我使用這些方法時,我的細胞看起來像。請告訴我你需要解決的任何想法。問題的關鍵是我在google doc的第二張圖片中展示的一個特例。

特殊情況背後的原因及其發生原因的深層次討論是在谷歌文檔。下面是谷歌文檔鏈接: https://docs.google.com/document/d/1tT43nE-1Wq8leRIaoQ29S0aQhZUWP88kIX3WlG_RcOg/edit?usp=sharing

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
if (indexPath.section==0) { //postcell 
    return 500.0; //TODO add some autolayout stuff for this case... 
} else { //comment cell 
    UIFont * font=[UIFont fontWithName:@"Helvetica Neue" size:13.0]; 
    NSIndexPath *adjustedIndexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section-1]; 
    BRComment *comment = [self.commentsController objectAtIndexPath:adjustedIndexPath]; 
    CGRect screenRect = [[UIScreen mainScreen] bounds]; 
    CGFloat screenWidth = screenRect.size.width; 

    //CommentCell * commentCell=(CommentCell *)[self.tableView cellForRowAtIndexPath:indexPath]; 
    CGSize labelHeight = [self heigtForCellwithString:comment.body andLabelWidth:screenWidth-78.0 withFont:font]; 
    return labelHeight.height; // the return height + your other view height 
} 
} 

-(CGSize)heigtForCellwithString:(NSString *)stringValue andLabelWidth:(CGFloat)labelWidth withFont:(UIFont *)font{ 
CGSize constraint = CGSizeMake(labelWidth,9999); // Replace 300 with your label width //TODO replace 
NSDictionary *attributes = @{NSFontAttributeName: font}; 
CGRect rect = [stringValue boundingRectWithSize:constraint 
             options:   (NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) 
            attributes:attributes 
             context:nil]; 
return rect.size; 

} 

回答

0

的iOS 8引入了超靈便UITableViewAutomaticDimension常量到UITableView。要自動調整單元格大小,只需從-tableView:heightForRowAtIndexPath:-tableView:estimatedHeightForRowAtIndexPath:中返回UITableViewAutomaticDimension

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return UITableViewAutomaticDimension; 
} 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return UITableViewAutomaticDimension; 
} 

瞧,您的細胞應該正確調整大小。請注意,如果您需要使用這些,則還會考慮單元格layoutMarginsindentationWidth/indentationLevel

相關問題