我创建一个 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 文档。但没有运气。我得到空字典。
我需要的唯一帮助是是否有人可以编写正确的代码来返回比对数据。
最佳答案
当您调用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;
请注意以下更改:
- 所请求属性的正确返回值
- 设置
范围
的正确长度 - 为
longestEffectiveRange:
传递NULL
,因为您不关心该值。
关于objective-c - 如何从 NSMutableAttributedString 获取 NSParagraphStyle 属性名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33453245/