如何从NSMutableAttributeString获取NSParagraphStyleAttributeName?

时间:2015-10-31 15:25:27

标签: objective-c nsattributedstring nsmutableattributedstring

我创建了一个NSMutableAttributedString,其对齐方式如下:

UIFont * font =  [UIFont systemFontOfSize:[UIFont labelFontSize]];
/// Make a copy of the default paragraph style
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
/// Set line break mode
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
/// Set text alignment
paragraphStyle.alignment = alignmentForString(textString) ;//NSTextAlignmentLeft;//NSTextAlignmentRight;// NSTextAlignmentNatural;//  NSTextAlignmentLeft;

NSDictionary *messageDrawRectAttributesDictionary = @{
                        NSFontAttributeName: font,
                        NSParagraphStyleAttributeName: paragraphStyle,
                        NSForegroundColorAttributeName:[UIColor blackColor]
                        };

NSMutableAttributedString * mutalbleAttributedString = [[NSMutableAttributedString alloc] initWithString:textString attributes:messageDrawRectAttributesDictionary];

我想知道(以后在应用中使用) 如何获得我在此字符串中设置的对齐方式。

我尝试了这段代码,却没有完全理解我在做什么:

NSRange range = NSMakeRange(0,mutalbleAttributedString.length-1);
NSDictionary * paraDic =[mutalbleAttributedString attribute:NSParagraphStyleAttributeName atIndex:0 longestEffectiveRange:&range inRange:range];

现在,我搜索了大量示例代码,并阅读了Apple文档。但没有运气。我得到空字典。

我唯一需要帮助的是,如果有人可以编写正确的代码,那么将返回对齐数据。

3 个答案:

答案 0 :(得分:3)

当您调用attribute:atIndex:longestEffectiveRange:inRange:时,返回值是请求的属性的值,而不是字典。另外,请勿为两个范围参数传递range

您的代码应该是这样的:

NSRange range = NSMakeRange(0, mutalbleAttributedString.length);
NSParagraphStyle *paraStyle = [mutalbleAttributedString attribute:NSParagraphStyleAttributeName atIndex:0 longestEffectiveRange:NULL inRange:range];
NSTextAlignment alignment = paraStyle.alignment;

请注意以下更改:

  • 请求的属性的正确返回值
  • 设置range
  • 的正确长度
  • NULL传递longestEffectiveRange:,因为您不关心该值。

答案 1 :(得分:0)

您可以从NSMutableAttributedString获取对齐方式,如下所示:

 NSRange range = NSMakeRange(0, mutableAttributedString.length);
 NSDictionary *attributes = [mutableAttributedString attributesAtIndex:0 effectiveRange:&range];
 NSMutableParagraphStyle *paragraphStyle = attributes[NSParagraphStyleAttributeName];
 NSTextAlignment alignment = paragraphStyle.alignment;

答案 2 :(得分:0)

Swift 5 示例:

var effectiveRange = NSMakeRange(0, attributedString.length)
let currentParagraphStyle: NSParagraphStyle = attributedText?.attribute(NSAttributedString.Key.paragraphStyle, at: 0, effectiveRange: &effectiveRange) as! NSParagraphStyle
let align = currentParagraphStyle.alignment
let lineSpacing = currentParagraphStyle.lineSpacing
let newParagraphStyle = currentParagraphStyle.lineHeightMultiple