objective-cnsattributedstringnsmutableattributedstring

How to get NSParagraphStyleAttributeName from NSMutableAttributeString?


I create an NSMutableAttributedString with alignment as follows:

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];

I want to know (for later use in the app) how to get what alignment I set in this string.

I tried this code, without understanding exactly what I'm doing:

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

Now, I search for a lot of sample code and I read the Apple docs. But no luck. I get empty dictionary.

The only help I need is if someone can just write the right code that will return me the data of the alignment.


Solution

  • When you call attribute:atIndex:longestEffectiveRange:inRange:, the return value is the value of the requested attribute, not a dictionary. Also, do not pass in range for both range parameters.

    Your code should be something like this:

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

    Note the following changes: