Cocoa NSTextField line spacing - objective-c

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.

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

NSMutableParagraphStyle remove old NSMutableAttributedString from UITextView

I try to add bullet point into UITextView in the start of the text but when i Add with this code the old attributedString and font and size not saved.
in this code :
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:currentTextViewEdit.text];
NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init];
[paragrahStyle setParagraphSpacing:4];
[paragrahStyle setParagraphSpacingBefore:3];
[paragrahStyle setFirstLineHeadIndent:0.0f]; // First line is the one with bullet point
[paragrahStyle setHeadIndent:10.5f]; // Set the indent for given bullet character and size font
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:NSMakeRange(0, [currentTextViewEdit.text length])];
currentTextViewEdit.attributedText = attributedString;
currentTextViewEdit.text = [NSString stringWithFormat:#"1.%#",currentTextViewEdit.text];
I try to add a NSMutableParagraphStyle but its remove the old NSMutableAttributedString that text have before.

Justify text for UILabel in iOS 9

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;

Cocoa get string width in pixels from font

I am trying to find the width in pixels of a string from the font and font size. I am currently using this code, but it is not working 100% of the time. Is there another way to do it?
NSSize textSize = [aTextLayer.string sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:#"Bank Gothic Medium", NSFontNameAttribute, [NSNumber numberWithFloat:aTextLayer.fontSize], NSFontSizeAttribute, nil]];
NSAttributedString is granted a -size method by the Application Kit Additions.
NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys:
#"Bank Gothic Medium", NSFontNameAttribute,
[NSNumber numberWithFloat:aTextLayer.fontSize], NSFontSizeAttribute,
nil];
NSAttributedString* attributedString = [[NSAttributedString alloc] initWithString:aTextLayer.string attributes:attributes];
NSSize size = attributedString.size;
Here is what i use to get the size of a string...
NSSize size = [#"Some text" sizeWithAttributes:[NSDictionary dictionaryWithObject:[NSFont fontWithName:#"Helvetica Neue Bold" size:24.0f] forKey:NSFontAttributeName]];
NOTE: If you are adding the string to a textfield, i have found that you need to add about 10 to size.width for it to fit.
Try using the actual NSFont (or UIFont) object instead of just the name of the font.
Here is yet another example:
NSString *test = [[NSString alloc] initWithFormat:#"%u:%u:%u.000", hours, minutes, seconds];
NSSize boundingSize = {100,300}; //I suppose this is the constraints?
NSRect boundingRect = [test boundingRectWithSize:boundingSize options:NULL attributes:stringAttributes];
point.x -= boundingRect.size.width; //This point points at the end of screen
[test drawAtPoint:point withAttributes:stringAttributes];
Here is for the stringAttributes, that may help noobs like me:
NSMutableDictionary *stringAttributes;
stringAttributes = [NSMutableDictionary dictionary];
[stringAttributes setObject:[NSFont fontWithName:#"Monaco" size:16] forKey:NSFontAttributeName];
[stringAttributes setObject:[NSColor whiteColor] forKey:NSForegroundColorAttributeName];
[stringAttributes setObject:[NSColor blackColor] forKey:NSBackgroundColorAttributeName];