【问题标题】:Calculate cell height for TextView with exclusion paths使用排除路径计算 TextView 的单元格高度
【发布时间】:2013-10-12 08:51:14
【问题描述】:

如果我在 UITableViewCell 中有一个带有排除路径的 TextView,我如何计算给定字符串的单元格高度?

【问题讨论】:

    标签: ios uitableview height uitextview textkit


    【解决方案1】:

    其实你不需要玩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;
    

    【讨论】:

    • 工作几乎完美。我必须在高度上加上 +1,才能正常工作,不知道为什么 :)
    【解决方案2】:

    我找到了一个我认为可能对其他人有帮助的解决方案。由于它不需要创建新的 NSTextContainer、NSLayoutManager 和 NSTextStorage 对象,它们已经作为 UITextView 的一部分实例化,我怀疑它会更有效。

    要计算使用排除路径和 NSAttributedString 的 UITextView 的大小,可以执行以下操作:

    // 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;
    

    Apple Documentation

    【讨论】:

    • 它似乎计算了正确的高度。但是何时调用此代码以及如何使单元格高度无效?
    猜你喜欢
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    相关资源
    最近更新 更多