我正在使用EGOTextView.I为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;
}
但是在缩放后键入文本时,似乎总是返回错误的高度。 有没有其他/更好的方法来确定我的属性字符串的正确高度?谢谢!
答案 0 :(得分:0)
我也在这种情况下运行,解决了它并编写了一个类别,在所有情况下都适用于我。请参阅我的答案如果您使用零作为高度,它不会将高度限制为任何高度。我为这个问题写了一个类别,在所有情况下都适用于我。见iOS UITableView with dynamic text and images rendered together (NSAttributedString + images)