How to set the font of NSMenu/NSMenuItems? - objective-c

I can’t figure out how to set the font/styling of my NSMenuItems in my NSMenu. I tried the setFont method on the NSMenu but it doesn’t seem to have any effect on the menu items. NSMenuItem doesn’t seem to have a setFont method. I would like for them all to have the same font/style so I would hope there’s just one property I can set somewhere.

They can have an attributed title, so you can set an attributed string as title with all it's attributed, font included:
NSMutableAttributedString* str =[[NSMutableAttributedString alloc]initWithString: #"Title"];
[str setAttributes: #{ NSFontAttributeName : [NSFont fontWithName: #"myFont" size: 12.0] } range: NSMakeRange(0, [str length])];
[label setAttributedString: str];

NSMenuItem has support for attributed strings as titles:
- (void)setAttributedTitle:(NSAttributedString *)string;
Example code:
NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle:#"Hi, how are you?" action:nil keyEquivalent:#""];
NSDictionary *attributes = #{
NSFontAttributeName: [NSFont fontWithName:#"Comic Sans MS" size:19.0],
NSForegroundColorAttributeName: [NSColor greenColor]
};
NSAttributedString *attributedTitle = [[NSAttributedString alloc] initWithString:[menuItem title] attributes:attributes];
[menuItem setAttributedTitle:attributedTitle];
Documentation: https://developer.apple.com/library/mac/#documentation/cocoa/reference/applicationkit/classes/nsmenuitem_class/reference/reference.html

+ menuBarFontOfSize: from NSFont is your friend here.
If you don't plan to change the font family, you should use [NSFont menuBarFontOfSize:12] to get the default font and set a new size.
If you are only changing the color, you still need to set the default font size back by doing [NSFont menuBarFontOfSize:0].
So to only change the NSMenuItem color:
NSDictionary *attributes = #{
NSFontAttributeName: [NSFont menuBarFontOfSize:0],
NSForegroundColorAttributeName: [NSColor greenColor]
};
NSAttributedString *attributedTitle = [[NSAttributedString alloc] initWithString:[menuItem title] attributes:attributes];
[menuItem setAttributedTitle:attributedTitle];

Actually [NSMenu setFont:] works for all menu items submenus (if last ones doesn't have their own font). Maybe you set attributed title before setting the menu font?
Realized it, after writing own procedure to iterate through menu items.
In case you need some custom processing (i.e. change font for not all items, or customize it for different items) here is a simple iterating code:
#implementation NSMenu (MenuAdditions)
- (void) changeMenuFont:(NSFont*)aFont
{
for (NSMenuItem* anItem in self.itemArray)
{
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:aFont forKey:NSFontAttributeName];
anItem.attributedTitle = [[[NSAttributedString alloc] initWithString:anItem.title attributes:attrsDictionary] autorelease];
if (anItem.submenu)
[anItem.submenu changeMenuFont:aFont];
}
}
#end

Related

how to Change message body text bold in message composer

hi I need to change text to bold in message composer body pls help me , I've tried with attributed text but I couldn't add
NSMutableAttributedString *yourAttributedString = [[NSMutableAttributedString alloc] initWithString:message];
NSString *boldString = #"hey";
NSRange boldRange = [message rangeOfString:boldString];
[yourAttributedString addAttribute: NSFontAttributeName value:[UIFont boldSystemFontOfSize:18] range:boldRange];
UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
lbl.attributedText = yourAttributedString;
MFMessageComposeViewController *messageComposeVC = [[MFMessageComposeViewController alloc] init];
messageComposeVC.messageComposeDelegate = self;
messageComposeVC.recipients = selectedContacts;
messageComposeVC.body = [lbl.attributedText string];
[self presentViewController:messageComposeVC animated:YES completion:nil];
I think it is better if you initiate a attribute to hold all your text attributes ( text size, font , colors ,weight ,styles) and add that when you are initializing the text , in your case "yourAttributedString" . Not sure if there is a specific reason to as why you do this so but try the following .
Use LocalizedStandardRangeofString instead or RangeOfString as you are
displaying this text.Check the "important" section in this documentation https://developer.apple.com/documentation/foundation/nsstring/1416849-rangeofstring?language=objc
//make an attributes dictionary here.
NSDictionary *stringAttributes = #{
NSFontAttributeName:[UIFont boldSystemFontOfSize:20]
};
NSString *message = #" message hey";
NSMutableAttributedString *yourAttributedString =[[NSMutableAttributedString alloc]initWithString:message];
NSString *boldString = #"hey";
NSRange range = [message localizedStandardRangeOfString:boldString];
[yourAttributedString addAttributes:stringAttributes range:range];
self.lbl.attributedText = yourAttributedString;

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

CATextLayer doesn't draw NSAttributedString background color

I have CATextLayer and want to set background color to part of the string. But setting background color to attributed string (NSBackgroundColorAttributeName) doesn't have any effect. Other attributes, such as foreground color, are applied correctly.
NSMutableAttributedString *str = [[[NSMutableAttributedString alloc] initWithString:#"Some Text"] autorelease];
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
[NSColor yellowColor], NSForegroundColorAttributeName,
[NSColor redColor], NSBackgroundColorAttributeName, nil];
[str setAttributes:attributes range:NSMakeRange(0, 3)];
textLayer.string = str;
First three symbols are drawn in yellow color, but background won't change. Any ideas?
I think that the CATextLayer class uses the CoreText API for its rendering. The CoreText API are very low-level and only support a subset of the NSAttributedString attributes. Unfortunately, the NSBackgroundColorAttributeName is not one of those. You have to deal with it manually (see this SO entry).

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)