本文介绍了确定最后一行的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多行的标签,lineBreakMode设置为UILineBreakModeWordWrap.如何确定最后一行的宽度?

I have a label with multiple lines, lineBreakMode is set to UILineBreakModeWordWrap. How can I determine width of last line?

推荐答案

自iOS 7.0起,您就可以使用此功能来做到这一点(也许您需要根据情况对文本容器进行更多调整):

Since iOS 7.0 you can do it using this function (Maybe you'll have to tweak text container a bit more for your case):

public func lastLineMaxX(message: NSAttributedString, labelWidth: CGFloat) -> CGFloat {
    // Create instances of NSLayoutManager, NSTextContainer and NSTextStorage
    let labelSize = CGSize(width: bubbleWidth, height: .infinity)
    let layoutManager = NSLayoutManager()
    let textContainer = NSTextContainer(size: labelSize)
    let textStorage = NSTextStorage(attributedString: message)

    // Configure layoutManager and textStorage
    layoutManager.addTextContainer(textContainer)
    textStorage.addLayoutManager(layoutManager)

    // Configure textContainer
    textContainer.lineFragmentPadding = 0.0
    textContainer.lineBreakMode = .byWordWrapping
    textContainer.maximumNumberOfLines = 0

    let lastGlyphIndex = layoutManager.glyphIndexForCharacter(at: message.length - 1)
    let lastLineFragmentRect = layoutManager.lineFragmentUsedRect(forGlyphAt: lastGlyphIndex,
                                                                  effectiveRange: nil)

    return lastLineFragmentRect.maxX
}

Objective-C:

Objective-C:

- (CGFloat)lastLineMaxXWithMessage:(NSAttributedString *)message labelWidth:(CGFloat)labelWidth
{
    CGSize labelSize = CGSizeMake(labelWidth, CGFLOAT_MAX);
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:labelSize];
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:message];
    [layoutManager addTextContainer:textContainer];
    [textStorage addLayoutManager:layoutManager];

    textContainer.lineFragmentPadding = 0;
    textContainer.lineBreakMode = NSLineBreakByWordWrapping;
    textContainer.maximumNumberOfLines = 0;
    NSUInteger lastGlyphIndex = [layoutManager glyphIndexForCharacterAtIndex:[message length] - 1];
    CGRect lastLineFragmentRect = [layoutManager lineFragmentUsedRectForGlyphAtIndex:lastGlyphIndex effectiveRange:nil];
    return CGRectGetMaxX(lastLineFragmentRect);
}

然后,您可以确定日期标签的最后一行是否有足够的空间

Then you can decide if there is enough place for your date label in the last line or not

用法示例:

// you definitely have to set at least the font to calculate the result
// maybe for your case you will also have to set other attributes
let attributedText = NSAttributedString(string: label.text, 
                                        attributes: [.font: label.font])
let lastLineMaxX = lastLineMaxX(message: attributedText, 
                                labelWidth: label.bounds.width)

这篇关于确定最后一行的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 14:56