Если у меня есть TextView с путями исключения в UITableViewCell
, как я могу рассчитать высоту ячейки для данной строки?
Вычислить высоту ячейки для TextView с путями исключения
Ответы (2)
Я нашел решение, которое, как мне кажется, может помочь другим. Поскольку для этого не требуется создание новых объектов NSTextContainer, NSLayoutManager и NSTextStorage, которые уже созданы как часть UITextView, я подозреваю, что это было бы более эффективно.
Чтобы вычислить размер UITextView, который использует пути исключений и NSAttributedString, можно сделать следующее:
// Assuming something like this...
UIBezierPath * exclusionPath = [UIBezierPath bezierPathWithRect:someRect];
self.textView.textContainer.exclusionPaths = @[exclusionPath];
NSAttributedString * attributedString = ...
self.textView.attributedString = attributedString;
...
// Use text container, layout manager, and text storage associated with the text view.
NSTextContainer * textContainer = self.textView.textContainer;
NSLayoutManager * layoutManager = textContainer.layoutManager;
NSTextStorage * textStorage = layoutManager.textStorage;
// Limit the width or height. In this case, limiting the width to 280.
textContainer.size = CGSizeMake(280.0, FLT_MAX);
[textStorage setAttributedString:attributedString];
// Because the layout manager performs layout lazily, on demand, you must force it to lay out the text, even though you don’t need the glyph range returned by this function.
[layoutManager glyphRangeForTextContainer:textContainer];
// Ask the layout manager for the height of the rectangle occupied by the laid-out text
CGFloat height = [layoutManager usedRectForTextContainer:textContainer].size.height;
person
Awesomeness
schedule
11.11.2013
На самом деле вам не нужно играть с textContainer
и layoutManager
. У меня это работает.
UIBezierPath *exclusionPath = [UIBezierPath bezierPathWithRect:imageViewFrame];
UITextView *tempTextView = [[UITextView alloc] init];
[tempTextView setFont:font];
tempTextView.textContainer.exclusionPaths = @[exclusionPath];
[tempTextView.textStorage replaceCharactersInRange:NSMakeRange(0, [tempTextView.text length]) withString:text];
CGRect textViewFrame = [tempTextView frame];
textViewFrame.size.height = [tempTextView sizeThatFits:CGSizeMake(290, FLT_MAX)].height;
return textViewFrame.size.height;
person
Dinesh Raja
schedule
14.05.2014
Работает практически идеально. Пришлось прибавить +1 к высоте, чтобы работала правильно, не знаю почему :)
- person Martin Berger; 04.04.2016