UITextView 動態高度計算(iOS7版)

 NSDictionary *attrsDictionary = [NSDictionarydictionaryWithObject:[UIFontsystemFontOfSize:kCellContentFontSize]

                                                                forKey:NSFontAttributeName];

    NSAttributedString *attributedText = [[[NSAttributedString alloc] initWithString:_contentStr attributes:attrsDictionary] autorelease];

    NSInteger detailHeight = [BZDataDealer textViewHeightForAttributedText:attributedText

                                                                  andWidth:detailLabelWidth];

    UITextView *detailTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, 35, detailLabelWidth, detailHeight+3)];  // 加3個像素

    detailTextView.scrollEnabled = NO;  // 是否容許滾動會影響高度的展現

    detailTextView.text = _contentStr;

    [containerView addSubview:detailTextView];

 

+ (NSInteger)textViewHeightForAttributedText:(NSAttributedString *)text andWidth:(CGFloat)width
{
    UITextView *textView = [[UITextView alloc] init];
    [textView setAttributedText:text];
    CGSize size = [textView sizeThatFits:CGSizeMake(width, FLT_MAX)];
    return (NSInteger)(size.height);
}

 

之前的方法用 先賦值, 再取textview的contentsize.height, iOS7後, 這個不能和了.spa

 

蘋果目前不少狀況下都是推薦使用 NSAttributedString 來計算一些數據.code

 

ps: 若是 blog

detailTextView.scrollEnabled = NO;  // 是否容許滾動會影響高度的展現

不容許滾動, 計算出的高度仍是會少一點. 因此上面加了3個像素.it

不知道是否是蘋果你妹的bug.io

相關文章
相關標籤/搜索