NSTextAlignmentJustified not working in iOS7 - ios7

I have an app which uses NSTextAlignmentJustified for an NSAttributedString. In iOS 6 everything is working great. But the same App running in iOS 7 (simulator or device makes no difference) is showing no Justify at all. Also the linespacing seems to have changed dramatically from iOS 6 to 7.
Anyone else encountered this problem? Is there any way to make a justified Textblock in iOS 7 (which works in iOS 6 too?)
Regards,
Markus

Ok, i kind of found a way to make the label Justifiy in iOS 7:
i simply set NSBaselineOffsetAttributeName to 0.
No idea why it works, but it works.
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
paragraphStyle.alignment = NSTextAlignmentJustified;
NSAttributedString *string = [[NSAttributedString alloc] initWithString:rawString
attributes:[NSDictionary dictionaryWithObjectsAndKeys:
paragraphStyle, NSParagraphStyleAttributeName ,
[NSNumber numberWithFloat:0],NSBaselineOffsetAttributeName,
nil]];

Setting firstLineHeadIndent on NSMutableParagraphStyle will also work too.
NSMutableParagraphStyle *paragraphStyles = [[NSMutableParagraphStyle alloc] init];
paragraphStyles.alignment = NSTextAlignmentJustified; // To justified text
paragraphStyles.firstLineHeadIndent = 0.05; // IMP: must have a value to make it work
NSString *stringTojustify = #"No one wakes up excited to see more advertising, no one goes to sleep thinking about the ads they’ll see tomorrow.";
NSDictionary *attributes = #{NSParagraphStyleAttributeName: paragraphStyles};
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:stringTojustify attributes:attributes];
self.lblQuote.attributedText = attributedString;
self.lblQuote.numberOfLines = 0;
[self.lblQuote sizeToFit];

Just for the record, you could also append a '\n' as first character for a plain UILabel.
self.text = [NSString stringWithFormat:#"\n%#",TextString];
{
CurFrame.origin.y -= FontSize;
self.frame = CurFrame;
}
self.textAlignment = NSTextAlignmentJustified;

Related

NSImage lockFocus and NSString size on retina display

I'm facing a weird issue, I'm drawing inside an NSImage using the following pseudo-code:
NSString* text = #"Hello world!";
NSDictionary *dict = [[[NSDictionary alloc] initWithObjectsAndKeys:[NSColor colorWithCGColor:textColor],NSForegroundColorAttributeName,font, NSFontAttributeName,nil] autorelease];
NSMutableAttributedString* str = [[[NSMutableAttributedString alloc] initWithString:text attributes:dict] autorelease];
NSSize stringSize = [str size];
NSImage* image = [[[NSImage alloc] initWithSize:stringSize] autorelease];
[image lockFocus];
NSRect drawRect = NSMakeRect(0,0,stringSize.width,stringSize.height);
[str drawInRect:drawRect];
[image unlockFocus];
Now the problem is that, with a dual monitor configuration, if I keep my retina display open, the string is mangled (I get half of the string drawn), while by simply closing my retina display and using only my cinema display, the string is drawn correctly. It's like the NSImage is getting the default context and some scaling factor from the retina display.
Do you have any hints ?
Thanks !
Ok, I will keep this for future reference, even there's something about displaying NSImage that covers the same aspect.
No matter what's your primary display but seems that the NSGraphicContext comes with an affine transformation that multiplies x 2 to address the retina resolution.
You just need to reset the affine transformations, before drawing into NSImage with:
NSAffineTransform *trans = [[[NSAffineTransform alloc] init] autorelease];
[trans set];

How do I center a number in a circle?

I'm trying to produce a set of custom page numbers. The current page number will be displayed. The others will simply be open circles.
Using the code below, I'm getting the desired results - except, with the new text attributes in iOS7, I cannot figure out how to center the number.
Any help will be appreciated.
Original iOS6 code:
[pageNumber drawInRect:CGRectMake(x,(self.frame.size.height-_currentPageDiameter)/2-1,_currentPageDiameter,_currentPageDiameter) withFont:[UIFont systemFontOfSize:_currentPageDiameter-2] lineBreakMode:UILineBreakModeCharacterWrap alignment:NSTextAlignmentCenter];
My iOS7 code:
NSString *pageNumber = [NSString stringWithFormat:#"%i", i+1];
CGContextSetFillColorWithColor(myContext, [[UIColor whiteColor] CGColor]);
UIFont* font = [UIFont systemFontOfSize:_currentPageDiameter-2];
NSDictionary *attrs = #{ NSForegroundColorAttributeName : [UIColor whiteColor],
NSFontAttributeName : font,
NSTextEffectAttributeName : NSTextEffectLetterpressStyle};
CGRect r = CGRectMake(x,(self.frame.size.height-_currentPageDiameter)/2-1,_currentPageDiameter,_currentPageDiameter);
[pageNumber drawInRect:r withAttributes:attrs];
The property you're missing for center alignment is defined the following way. I also added the line break mode you had defined on the iOS6 code:
NSMutableParagraphStyle *paragrapStyle = [[NSMutableParagraphStyle alloc] init];
paragrapStyle.alignment = NSTextAlignmentCenter;
paragrapStyle.lineBreakMode = NSLineBreakByCharWrapping;
You just place them in the attributes dictionary under the key:
NSArray *attrs = #{
NSParagraphStyleAttributeName : paragraphStyle,
...
};

drawInRect:withFont:lineBreakMode:alignment deprecation in IOS 7

I have a message of deprecated method.
The line of code is this one :
[string drawInRect:drawArea withFont:uifont lineBreakMode:linebreaks[lineBreakMode] alignment:alignments[hAlignment]];
So I want to replace it with this code :
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
paragraphStyle.alignment = NSTextAlignmentCenter;
NSDictionary *attributes = #{ NSFontAttributeName: uifont,
NSParagraphStyleAttributeName: paragraphStyle};
[string drawInRect:drawArea withAttributes:attributes];
After this replacement, the warning is not here anymore. But, all my text is invisible. For example, I have a text "Options" which is not visible (but I can still click on it).
Someone can help on this please?
Regard

NSTextAttachment with text flowing around it

I have a TextKit based editor with support to adding images. I want to show each image on separate lines.
My code looks like this (Thank you TextEdit), in my subclass of NSTextStorage
- (void)addImageAssets:(NSArray *)allAssets atRange:(NSRange)range;
{
NSMutableAttributedString *attachments = [NSMutableAttributedString new];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.alignment = NSTextAlignmentCenter;
paragraphStyle.lineSpacing = 20.0f;
for (ALAsset *newAsset in allAssets)
{
UIImage *theImage = [UIImage imageWithCGImage:newAsset.aspectRatioThumbnail];
NSTextAttachment *textAttachment = [NSTextAttachment new];
textAttachment.image = theImage;
NSMutableAttributedString *replacementString = [NSMutableAttributedString new];
[replacementString appendAttributedString:[NSAttributedString attributedStringWithAttachment:textAttachment]];
[replacementString addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0, [replacementString length])];
[attachments appendAttributedString:replacementString];
}
_isEditing = YES;
[self beginEditing];
[_backingStore replaceCharactersInRange:range
withAttributedString:attachments];
[self edited:NSTextStorageEditedAttributes
range:range changeInLength:allAssets.count];
[super processEditing];
[self endEditing];
_isEditing = NO;
}
(the _isEditing is a boolean flag used for book-keeping)
The output looks like this Output http://take.ms/QCvRK
I have tried various parameters on the NSMutableParagraphStyle but I couldn't get a line break after each image.
Appending a line break ("\r") around the text attachment will result in a glyph error
!!! _NSLayoutTreeLineFragmentRectForGlyphAtIndex invalid glyph index 1
!!! _NSGlyphTreeInvalidateGlyphsForCharacterRange invalid char range 1
!!! _NSGlyphTreeInvalidateGlyphsForCharacterRange character count mismatch
!!! _NSLayoutTreeLineFragmentRectForGlyphAtIndex invalid glyph index 0
!!! _NSLayoutTreeLineFragmentRectForGlyphAtIndex invalid glyph index 0
!!! _NSLayoutTreeLineFragmentUsedRectForGlyphAtIndex invalid glyph index 2147483647
I tried to subclass the NSTextAttachment to over-ride the attachmentBoundsForTextContainer:proposedLineFragment:glyphPosition:characterIndex: so that the width is set to the device width, this resulted in the attached image looking blown up.
Any suggestion on how I can introduce a line break right after each image ? Also it would be great if I can get the text to flow around the image attachments.
Thanks in advance.

How to get the width of an NSString?

I am trying to get the width of an NSString (ex. NSString *myString = #"hello"). Is there a way to do this?
Thanks.
Here's a relatively simple approach. Just create an NSAttributedString with the appropriate font and ask for its size:
- (CGFloat)widthOfString:(NSString *)string withFont:(NSFont *)font {
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
return [[[NSAttributedString alloc] initWithString:string attributes:attributes] size].width;
}
UIFont * font = [UIFont systemFontOfSize:15];
CGSize stringSize = [aString sizeWithFont:font];
CGFloat width = stringSize.width;
Using the UILabel's attributed string:
- (CGSize)getStringSizeWithText:(NSString *)string font:(UIFont *)font{
UILabel *label = [[UILabel alloc] init];
label.text = string;
label.font = font;
return label.attributedText.size;
}
Send the string a sizeWithAttributes: message, passing a dictionary containing the attributes with which you want to measure the string.
i dont know if you are suppose to use this in cocoa touch. if it is, then:
- (CGFloat)widthOfString:(NSString *)string withFont:(NSFont *)font {
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
return [[[NSAttributedString alloc] initWithString:string attributes:attributes] size].width;
}
wont work.
in cocoa touch, you gotta add coretext framework and import the header
and write your code like this:
UIFont *font = [UIFont fontWithName:#"HelveticaNeue-BoldItalic" size:DEFAULT_FONT_SIZE];
// NSLog(#"%#", NSFontAttributeName);
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, (NSString *)kCTFontAttributeName, nil];
but, GEE!!!!!
NSMutableAttributedString *as = [[NSMutableAttributedString alloc] initWithString:self.caption attributes:attributes];
[as size].width;
there's no size this method in NSMutableAttributedString!
finally, this would work
[self.caption sizeWithFont:font].width
as for ios 7 and up this is the correct way:
NSString * buttonTitle = #"demo title";
CGSize stringSize = [buttonTitle sizeWithAttributes:#{NSFontAttributeName: [UIFont systemFontOfSize:17.0f]}];
This works with iOS 14.5
Objective-C
Define attributes:
NSDictionary *attributes = #{
NSFontAttributeName: [UIFont fontWithName:#"Helvetica" size:25],
NSStrokeWidthAttributeName: #(0),
NSStrokeColorAttributeName: [UIColor blackColor]
};
Get width and height:
- (CGFloat)widthOfString:(NSString *)string {
CGSize stringSize = [string sizeWithAttributes:attributes];
return stringSize.width;
}
- (CGFloat)heightOfString:(NSString *)string {
CGSize stringSize = [string sizeWithAttributes:attributes];
return stringSize.height;
}
Sorry my question was not detailed enough and is not exactly what I'm trying to do. I am using a text storage, layout manager and a text container. The solution is to use the layout manager to determine the rectangle that bounds the rect. Here is the code.
NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:#"hello"];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
NSTextContainer *textContainer = [[NSTextContainer alloc] init];
[layoutManager addTextContainer:textContainer];
[textContainer release];
[textStorage addLayoutManager:layoutManager];
[layoutManager release];
//Figure out the bounding rectangle
NSRect stringRect = [layoutManager boundingRectForGlyphRange:NSMakeRange(0, [layoutManager numberOfGlyphs]) inTextContainer:textContainer];
UIKit has a nice addition to NSString, making sizeWithAttributes: a bit lighter:
CGSize titleSize = [title sizeWithFont:titleFont
constrainedToSize:contentCellSize
lineBreakMode:UILineBreakModeWordWrap];
Here's Stephen's solution in Clozure Common Lisp, when using the Objective C bridge. I came across this post when searching for a solution, and I just rewrote Stephen's version which worked fine for me. Others using Clozure might find this helpful:
(defun string-width (str font)
(let* ((dict (#/dictionaryWithObjectsAndKeys: ns:ns-mutable-dictionary
font #$NSFontAttributeName
ccl:+null-ptr+))
(attr (#/initWithString:attributes: (#/alloc ns:ns-attributed-string)
(ccl::%make-nsstring str)
dict))
(size (#/size attr)))
(ns:ns-size-width size)))
This will work. You can try it.
NSDictionary *attrDict = #{NSFontAttributeName : [GenericUtility getOpenSansRegularFontSize:12]};
CGSize stringBoundingBox = [selectedReservationModel.DateLabel sizeWithAttributes: attrDict];
lblDeliveryDateWidth = stringBoundingBox.width;
Just in case you are wondering how to check a label size, you should use the UIFont, instead of the NSFont (not even sure if exists)