0

我正在使用 EGOTextView。我为 viewForZoomingInScrollView 设置了 textContentView。当我将其缩小并键入时。它有时会返回不正确的高度。这是我正在做的事情:

CTFramesetterRef framesetter = _framesetter;
CFAttributedStringRef attributedStringRef=(CFAttributedStringRef)self.attributedString;
_framesetter = CTFramesetterCreateWithAttributedString(attributedStringRef);

if (framesetter!=NULL) {
    CFRelease(framesetter);
}
CGRect rect = self.textContextView.frame;

CGFloat height = [self heightForAttributedString:self.attributedString forWidth:rect.size.width];
rect.size.height = (height + self.font.lineHeight * 2) * pageScale;
//pageScale is the scale scrollview end zooming


- (CGFloat)boundingHeightForWidth:(CGFloat)width {

CGSize suggestedSize = CTFramesetterSuggestFrameSizeWithConstraints(_framesetter, CFRangeMake(0, 0), NULL, CGSizeMake(width , CGFLOAT_MAX), NULL);
return suggestedSize.height;
}

我也尝试这种方法:

+(CGFloat)heightForAttributedString:(NSAttributedString *)attrString forWidth:(CGFloat)inWidth
{

CGFloat H = 0;

// Create the framesetter with the attributed string.
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString( (CFMutableAttributedStringRef) attrString);

CGRect box = CGRectMake(0,0, inWidth, CGFLOAT_MAX);

CFIndex startIndex = 0;

CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, box);

// Create a frame for this column and draw it.
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(startIndex, 0), path, NULL);

// Start the next frame at the first character not visible in this frame.
//CFRange frameRange = CTFrameGetVisibleStringRange(frame);
//startIndex += frameRange.length;

CFArrayRef lineArray = CTFrameGetLines(frame);
CFIndex j = 0, lineCount = CFArrayGetCount(lineArray);
CGFloat h, ascent, descent, leading;

for (j=0; j < lineCount; j++)
{
    CTLineRef currentLine = (CTLineRef)CFArrayGetValueAtIndex(lineArray, j);
    CTLineGetTypographicBounds(currentLine, &ascent, &descent, &leading);
    h = ascent + descent + leading;
    NSLog(@"%f", h);
    H+=h;
}

CFRelease(frame);
CFRelease(path);
CFRelease(framesetter);


return H;
}

但是,当您在缩放后输入文本时,它似乎总是返回错误的高度。有没有其他/更好的方法来确定我的属性字符串的正确高度?谢谢!

4

1 回答 1

0

我也在这种情况下运行,解决了它并编写了一个类别,在所有情况下都适用于我。如果您使用零作为高度,请参阅我的答案,它不会将高度限制为任何高度。我为这个问题写了一个类别,在所有情况下都对我有用。查看iOS UITableView 与动态文本和图像一起呈现(NSAttributedString + 图像)

于 2014-03-09T02:46:40.193 回答