14 Temmuz 2015 Salı

Attributed text kullanırken TextView'ın toplam metin yüksekliğini hesaplama

Ne yaptıysam textView.contentSize.height hep yanlış değerler geliyordu. Biyerlerden aşağıdaki kodu buldum ve şıkır şıkır çalışıyor.

- (CGFloat)measureHeightOfUITextView:(UITextView *)aTextView
{
    if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1)
    {
        // This is the code for iOS 7. contentSize no longer returns the correct value, so
        // we have to calculate it.
        //
        // This is partly borrowed from HPGrowingTextView, but I've replaced the
        // magic fudge factors with the calculated values (having worked out where
        // they came from)
        
        CGRect frame = aTextView.bounds;
        
        // Take account of the padding added around the text.
        
        UIEdgeInsets textContainerInsets = aTextView.textContainerInset;
        UIEdgeInsets contentInsets = aTextView.contentInset;
        
        CGFloat leftRightPadding = textContainerInsets.left + textContainerInsets.right + aTextView.textContainer.lineFragmentPadding * 2 + contentInsets.left + contentInsets.right;
        CGFloat topBottomPadding = textContainerInsets.top + textContainerInsets.bottom + contentInsets.top + contentInsets.bottom;
        
        frame.size.width -= leftRightPadding;
        frame.size.height -= topBottomPadding;
        
        NSString *textToMeasure = aTextView.text;
        if ([textToMeasure hasSuffix:@"\n"])
        {
            textToMeasure = [NSString stringWithFormat:@"%@-", aTextView.text];
        }
        
        // NSString class method: boundingRectWithSize:options:attributes:context is
        // available only on ios7.0 sdk.
        
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
        
        NSDictionary *attributes = @{ NSFontAttributeName: aTextView.font, NSParagraphStyleAttributeName : paragraphStyle };
        
        CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT)
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                               attributes:attributes
                                                  context:nil];
        
        CGFloat measuredHeight = ceilf(CGRectGetHeight(size) + topBottomPadding);
        return measuredHeight;
    }
    else
    {
        return aTextView.contentSize.height;
    }
}

Hiç yorum yok:

Yorum Gönder