Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSAttributedString justified text (without stretching words)

I'm using justified text for my NSAttributedString in my UITextView:

var paragraphStyle = NSMutableParagraphStyle()        
paragraphStyle.alignment = NSTextAlignment.Justified;
normalAttributes.setObject(paragraphStyle, forKey: NSParagraphStyleAttributeName)

The problem is that it stretches some words in order to achieve the justified alignment, instead of just stretching the spaces between the words. I find this very distracting and know there is a way to do such that words are not stretched, but only the spacing. Below is a screenshot from my app, followed by one from an app with some of the same functionality that also uses justified text and the exact same font.

enter image description here

enter image description here

How do I achieve the same effect?

Any help would be greatly appreciated.

like image 710
Casey Perkins Avatar asked Mar 05 '15 18:03

Casey Perkins


1 Answers

There is a nasty trick which you can use.

You can use a UIWebView and css to do the alignment the way you want. Here is a sample:

NSString *css = [NSString stringWithFormat:
                 @"<html><head><style>body { background-color: white; text-align: %@; font-size: %ipx; color: black;} a { color: #172983; } </style></head><body>",
                 @"justify",
                 11];

NSMutableString *desc = [NSMutableString stringWithFormat:@"%@%@%@",
                         css,
                         @"15 Προσέχετε ἀπὸ τῶν ψευδοπροφητῶν͵ οἵτινες ἔρχονται πρὸς ὑμᾶς ἐν ἐνδύμασι προβάτων͵ ἔσωθεν δέ εἰσι λύκοι ἅρπαγες. 16 ἀπὸ τῶν καρπῶν αὐτῶν",
                         @"</body></html>"];

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(20, 80, 150, 100)];
[self.view addSubview:webView];
[webView loadHTMLString:desc baseURL:nil];

And here is the result:

WebView Text Alignment

like image 60
Lefteris Avatar answered Oct 24 '22 20:10

Lefteris