NSAttributedString Writing Direction

2019-02-23 07:58发布

问题:

I am trying to change the write direction in an NSAttributedString. However, I have a really hard time figuring out how to do it.

CTFontRef fontRef = CTFontCreateWithName((CFStringRef)@"ArialRoundedMTBold", 16, NULL);

NSDictionary *attrDictionary = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)fontRef,(NSString *)kCTFontAttributeName, nil];
CFRelease(fontRef);

NSAttributedString *attString=[[NSAttributedString alloc] initWithString:self.stringMap attributes:attrDictionary];

self.attString = attString;

This is the code in which I initialise my NSAttributedString and I have read about the constant kCTWritingDirectionRightToLeft and I feel like I have to put it in somewhere but I can figure out where and how.

Anyone got any suggestions?

回答1:

I read more carefully the doc.

I'll use NSFontAttributeName and NSWritingDirectionAttributeName since I'm more confortable with them than using all the bridge stuff, and also shorthand syntax.

So NSWritingDirectionAttributeName waits for a NSArray of NSNumbers. That was the issue. One of theses numbers must be a NSWritingDirection (LeftToRight or RightToLeft), and the other a NSTextWritingDirection (Embedding or Override).

So, the combinations possibles are (and I think you're looking for the forth one):

NSDictionary *attrDictionary = @{NSFontAttributeName:font,
                                 NSWritingDirectionAttributeName:@[@(NSWritingDirectionRightToLeft | NSTextWritingDirectionOverride)]};

NSDictionary *attrDictionary = @{NSFontAttributeName:font,
                                 NSWritingDirectionAttributeName:@[@(NSWritingDirectionLeftToRight | NSTextWritingDirectionEmbedding)]};

NSDictionary *attrDictionary = @{NSFontAttributeName:font,
                                 NSWritingDirectionAttributeName:@[@(NSWritingDirectionLeftToRight | NSTextWritingDirectionOverride)]};

NSDictionary *attrDictionary = @{NSFontAttributeName:font,
                                 NSWritingDirectionAttributeName:@[@(NSWritingDirectionRightToLeft | NSTextWritingDirectionOverride)]};

Source: Documentation of NSWritingDirectionAttributeName