objective-c - 如何从 NSMutableAttributedString 获取 NSParagraphStyle 属性名称?

标签 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 文档。但没有运气。我得到空字典。

我需要的唯一帮助是是否有人可以编写正确的代码来返回比对数据。

最佳答案

当您调用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/

相关文章:

ios - 从中间截断 NSString 的子字符串

ios - 按下按钮时在类中使用数据 Objective-C/iOS

iphone - 将应用程序移动到新计算机将无法运行

iOS:在 html 属性字符串中调整图像大小

ios - NSMutableAttributedString paragraphStyle 不适用

ios - 将 NSAttributed 文本附加到 UITextview

ios - 多行 UILabel 上的 NSAttributedString 切断第一行

objective-c - 从 View Controller 传递后,传递的托管对象上下文为空

ios - 使用 iPhone Hooks 将图片/视频从照片上传到 Instagram

ios - 具有复杂格式的 UITableViewCell 的最佳方法