UILabel中右对齐文本的边界矩形错误

时间:2018-08-12 16:45:58

标签: ios uilabel

- (CGRect)boundingRectForGlyphRange:(NSRange)glyphRange inTextContainer:(NSTextContainer *)container;
当属性文本在UILabel中右对齐时,

返回字形范围的错误rect。请问该如何解决?

在UILabel上点击时计算属性文本的边界rect的代码(在UILabel中将textAlignment设置为right)

- (void)tap:(UITapGestureRecognizer *)recognizer {
    UILabel *label = (UILabel *)recognizer.view;
    CGSize labelSize = recognizer.view.bounds.size;

    NSTextContainer *container = [[NSTextContainer alloc] initWithSize:labelSize];
    container.lineFragmentPadding = 0.0;
    container.lineBreakMode = label.lineBreakMode;
    container.maximumNumberOfLines = label.numberOfLines;

    NSLayoutManager *manager = [NSLayoutManager new];
    [manager addTextContainer:container];

    NSTextStorage *storage = [[NSTextStorage alloc] initWithAttributedString:label.attributedText];
    [storage addLayoutManager:manager];

    CGPoint touchPoint = [recognizer locationInView:label];
    NSInteger indexOfCharacter = [manager characterIndexForPoint:touchPoint
                                                 inTextContainer:container
                        fractionOfDistanceBetweenInsertionPoints:nil];

    NSRange range = NSMakeRange(indexOfCharacter, 1);
    NSRange glyphRange;
    [manager characterRangeForGlyphRange:range actualGlyphRange:&glyphRange];
    CGRect rect = [manager boundingRectForGlyphRange:glyphRange inTextContainer:container];
}

2 个答案:

答案 0 :(得分:1)

问题是您要设置标签的texttextAlignment,然后将标签的attributedText拉出并将其交给文本工具包堆栈,以为它神奇地将标签配置转换为属性字符串。不是!

如果您希望文本工具包堆栈中的右对齐文本显示为右对齐,请设置标签的attributedText only ,并为其添加诸如右对齐段落的功能样式。

答案 1 :(得分:0)

解决了这个问题!

问题是使用UILabel的textAlignment属性使标签右对齐。如评论中所述,label.attributedText一无所知。

相反,使用NSParagraphStyleAttributeName作为添加文本对齐方式:

NSMutableAttributedString *mutableString = [NSMutableAttributedString new];
//Add to your string
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setAlignment:NSTextAlignmentRight];
[mutableString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, mutableString.length)];
label.attributedText = mutableString;