Justify text for UILabel in iOS 9 - objective-c

I have found solution to justify text in UILabel for versions up to iOS 8.4 through attributed strings: set label string as attributed and modify hyphenation value as presented below.
This solution stopped working on iOS 9 (text shows left aligned). I need other working solution which supports from iOS 7 or at least works at iOS 9 (would add 'if' somewhere)

Update:
It seems that adding a #"locale" key to attributes of NSAttributedString may help. See here.
Original answer:
You can always use NSAttributedString here:
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.hyphenationFactor = 1;
paragraphStyle.alignment = NSTextAlignmentJustified;
NSDictionary *attributes = #{
NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleBody],
NSParagraphStyleAttributeName: paragraphStyle
};
NSString *string = #"your text here";
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:string attributes:attributes];
self.label.attributedText = attributedString;
self.label.numberOfLines = 0;

Related

Calculate size of NSAttributedString from HTML

I am using a UITextView to display an NSAttributedString from some given HTML, which can includes elements such as bold, italicized, lists, marked, super & subscript, etc.
Currently the code below works pretty well for just paragraphs of text, but once I start adding more complicated elements such as lists and line breaks, the sizing is completely off.
// Create the NSMutableAttributedString from given HTML
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *options = #{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: #(NSUTF8StringEncoding)};
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithData:data options:options
documentAttributes:nil error:nil];
// Max size for the text container (no limit on height)
CGSize bounds = CGSizeMake(320.0, CGFLOAT_MAX);
// Set the font and size for better rendering results
UIFont *font = [UIFont fontWithName:#"Roboto" size:14.0];
NSDictionary *attrFont = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
NSRange range = NSMakeRange(0, str.length);
[str addAttributes:attrFont range:range];
// Calcualte the size of the UITextView based on the above parameters
CGRect rect = [str boundingRectWithSize:bounds options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading| NSStringDrawingUsesDeviceMetrics context:nil];
I've done some searching and found this thread, but after trying what is suggested over there it still doesn't appear to be working, wondering if anyone knows of a better way to do this?
Calculate Height Of NSAttributedString Containing HTML
Ok after much fiddling around I found that the sizes are actually correct, but the UITextView has some padding / insets that cause the overflow. Setting the following on the textView fixed the problem
[self.textView setTextContainerInset:UIEdgeInsetsZero];
self.textView.textContainer.lineFragmentPadding = 0;

Objective C label line spacing?

Is there a way to set the distance of two lines within a UILabel?
I tried to do it within Interface Builder but without success.
The code you want will be something like this:
NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString:#"Sample text"];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:24];
[attrString addAttribute:NSParagraphStyleAttributeName
value:style
range:NSMakeRange(0, strLength)];
uiLabel.attributedText = attrString;
You can use NSAttributedString to add spacing between two lines within a UILabel:
NSString *labelText = #"My String";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:20];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
cell.label.attributedText = attributedString ;
OR
If you are using storyboard then you can control line spacing in the storyboard by selecting text type is attributed and add spacing value:
Since iOS 6, Apple added NSAttributedString to UIKit, making it possible to use NSParagraphStyle to change the line spacing.
Alternatively, you can do this via Storyboards using Attributed Text and then clicking the ... symbol. See link below for screenshot.
https://i.stack.imgur.com/aiNfR.png

Why Does Kerning fail for NSAttributedString in IOS7

My app has a UILabel formatted as an NSAttributedString with
the attribute: 'NSKernAttributeName #1.9,'
When the below code is compiled on iPad running IOS6, the kern works as expected.
When compiled on iPad running IOS7, no kerning occurs.
I have filed Bug at Apple Developer site. #15108371 - No Response yet
NSString *formattedNumber;
NSNumber *scoreNum = [[NSNumber alloc] initWithLongLong:thisScore];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterPadBeforeSuffix;
formatter.formatWidth = 10;
formatter.paddingCharacter = #"0";
formatter.numberStyle = NSNumberFormatterDecimalStyle;
formatter.usesGroupingSeparator = NO;
formattedNumber = [formatter stringFromNumber:scoreNum];
//Creat atributed string of formated number.
NSShadow *textShadow = [[NSShadow alloc] init];
textShadow.shadowColor = [UIColor colorWithRed:0.5 green:0.7 blue:1 alpha:1.0];
textShadow.shadowBlurRadius = 5.0;
textShadow.shadowOffset = CGSizeMake(0,0);
NSAttributedString *pHighScoreStyle = [[NSAttributedString alloc] initWithString:formattedNumber attributes: #{
NSFontAttributeName: [UIFont fontWithName:#"courier" size:16],
NSForegroundColorAttributeName: [UIColor colorWithRed:0.6 green:0.8 blue:1.0 alpha:0.8],
NSKernAttributeName: #1.9,
NSShadowAttributeName: textShadow } ];
//Change the disply value.
runningScore.attributedText = pHighScoreStyle;
OK. I had the same problem (see comment above). It depends on the font (I used Courier as well). For some strange reason Courier does not support kerning (in iOS7!). Use CourierNewPSMT and everything works as expected .... at least for me.
BTW: Here is a nice list of fonts on the iphone:
http://iosfonts.com/

Convert NSString to HTML and set HTML text into UILabel [duplicate]

This question already has answers here:
How to create a UILabel or UITextView with bold and normal text in it?
(5 answers)
Closed 9 years ago.
Is it possible to convert a NSString to html and set as a label?
The code below shows the NSString I want to set finalPrice as bold text and finalStr&shipping string as normal text
NSString *myText = [NSString
stringWithFormat:
#"%#\nFinal price including $%.2f Shipping and all discount: <b>$%.2f</b>",
finalStr,shipping,finalPrice];
lbl.text = myText;
I want to set multiple color and multiple text type into same dyanamic label.
use following label for bold effects. Or you can get code from that class.
DAAttributedStringUtils
and also see this
Different Label
Edit
NSString *myText = [NSString stringWithFormat:#"%#\nFinal price including $%.2f Shipping and all discount: %%B$%.2f%%b",finalStr,shipping,finalPrice];
DAAttributedLabel* lbl = [[DAAttributedLabel alloc] initWithFrame:CGRectMake(30.0f, 30.0f, 260.0f, 24.0f)];
lbl.backgroundColor = [UIColor colorWithRed:0.9f green:0.9f blue:1.0f alpha:1.0f];
lbl.text = (id)[formatter formatString:myText];
[self.view addSubview:lbl];
Try using NSAttributedString
There are already several questions around this here like
How do you use NSAttributedString?
NSString * textString = #"Hello Bold";
NSInteger _stringLength = [textString length];
NSMutableAttributedString * attString = [[NSMutableAttributedString alloc] initWithString:textString];
[attString addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"Helvetica" size:14.0f]; range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"Helvetica-Bold" size:14.0f]; range:NSMakeRange(6, 4)];
myLabel.attributedText = attString;
(code not tested)
Edit:
label.attributedText is only available for iOS 6.0+
FYI, the answer above suggesting the use of DAAttributedStringUtils and DAAttributedLabel didn't mention that these are convenience classes for the use of NSAttributedString. They make formatting NSAttributedString instances a little easier. As an example, here's how to do the same formatting described about by HAS using DAAttributedStringUtils:
float finalPrice = 34.99, shipping = 4.99;
// Setup the formatter
DAAttributedStringFormatter* formatter = [[DAAttributedStringFormatter alloc] init];
formatter.defaultFontFamily = #"Georgia";
formatter.defaultFontSize = 12.0f;
formatter.colors = #[ [UIColor blackColor], [UIColor redColor] ];
NSAttributedString* attrStr = [formatter formatString:#"%0C%0FRed Courier Text %1C%1FBlue Arial Text %0CRed Arial Text"];
// setup base strings
NSString *finalStr = #"Some Text. ";
NSString *shippingAttributed = [NSString stringWithFormat:#"%%B%%1C$%.2f%%b%%c", shipping];
NSString *middleText0 = #"Final price including ";
NSString *middleText1 = #" Shipping and all discount: ";
NSString *finalPriceAttributed = [NSString stringWithFormat:#"%%B%%1C$%.2f%%b%%c", finalPrice];
// Format the strings
self.label.attributedText = [formatter formatString:[NSString stringWithFormat:#"%#%#%%B%%1C%#%%b%%c%#%%B%%1C%#", finalStr, shippingAttributed, middleText0, middleText1, finalPriceAttributed];
Somewhat less code, and I think easier to understand. FYI, the formatter string in the last line contains codes that are used to modify the format of portions of the string. Those codes use double percents (

Cocoa NSTextField line spacing

I'm struggling with a very simple problem, I've several NSTextField ( I can't use NSTextView right now) and I need to change the line spacing of the displayed text.
What can I do to reduce row height or line spacing? Shrinking the font size isn't an option.
Any help would be really appreciated!
Have a great weekend,
!)
For reference you want to read this description of paragraph styles: Cocoa Paragraph Styles and note that everything in there is additional space added between lines, between paragraphs, before paragraphs, etc. You can set the values in your NSMutableParagraphStyle to zero but no lower.
To further shrink the spacing between lines, use setMaximumLineHeight, thanks to "6 1" for the code (I've add the setMaximumLineHeight):
NSString *title = #"title here";
NSFont *bold14 = [NSFont boldSystemFontOfSize:14.0];
NSColor *textColor = [NSColor redColor];
NSMutableParagraphStyle *textParagraph = [[NSMutableParagraphStyle alloc] init];
[textParagraph setLineSpacing:10.0]; // this sets the space BETWEEN lines to 10points
[textParagraph setMaximumLineHeight:12.0]; this sets the MAXIMUM height of the lines to 12points
NSDictionary *attrDic = [NSDictionary dictionaryWithObjectsAndKeys:bold14, NSFontAttributeName, textColor, NSForegroundColorAttributeName, textParagraph, NSParagraphStyleAttributeName, nil];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:title attributes:attrDic];
[self.titleField setAllowsEditingTextAttributes:YES];
[self.titleField setAttributedStringValue:attrString];
Swift version of Jason Harrison's excellent Obj-c answer:
let title:String = "title here"
let bold14:NSFont = NSFont.boldSystemFontOfSize(14.0)
let textColor:NSColor = NSColor.redColor()
let textParagraph:NSMutableParagraphStyle = NSMutableParagraphStyle()
textParagraph.lineSpacing = 10.0 /*this sets the space BETWEEN lines to 10points*/
textParagraph.maximumLineHeight = 12.0/*this sets the MAXIMUM height of the lines to 12points*/
let attribs = [NSFontAttributeName:bold14,NSForegroundColorAttributeName:textColor,NSParagraphStyleAttributeName:textParagraph]
let attrString:NSAttributedString = NSAttributedString.init(string: title, attributes: attribs)
textField.attributedStringValue = attrString
you can use NSAttributedString to show the text.
NSFont *bold14 = [NSFont boldSystemFontOfSize:14.0];
NSColor *textColor = [NSColor redColor];
NSMutableParagraphStyle *textParagraph = [[NSMutableParagraphStyle alloc] init];
[textParagraph setLineSpacing:10.0];
NSDictionary *attrDic = [NSDictionary dictionaryWithObjectsAndKeys:bold14, NSFontAttributeName, textColor, NSForegroundColorAttributeName, textParagraph, NSParagraphStyleAttributeName, nil];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:title attributes:attrDic];
[self.titleField setAllowsEditingTextAttributes:YES];
[self.titleField setAttributedStringValue:attrString];
It's ok to display text not for inputing text. And I only know how to set line spacing.