NSMenuItem : Truncation and setLineBreakMode
-
26-05-2021 - |
Question
I'm creating several menu items programmatically like this :
NSMenuItem* newItem = [[NSMenuItem alloc] initWithTitle:t action:s keyEquivalent:e];
[newItem setTarget:target];
[newItem setEnabled:YES];
[self addItem:newItem];
And I want to truncate their contents (in the middle) like that :
Some really really long title ---> Some rea...title
I've read about using the setLineBreakMode
method... but HOW? (I think I'm doing something wrong :-S)
Solution
A possible solution consists to use NSAttributedString and the [NSMenuDelegate confinementRectForMenu:onScreen:screen];
confinementRectForMenu is necessary to set the max width you want
Just to show you an example without delegate below I show a menuitem with a very big font
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle]
mutableCopy];
[style setLineBreakMode:NSLineBreakByTruncatingMiddle];
NSDictionary* paragraphStyle = [[NSDictionary alloc] initWithObjectsAndKeys:
style, NSParagraphStyleAttributeName,
[NSFont fontWithName:@"Lucida Grande" size:43.0f],
NSFontAttributeName,
nil];
[style release];
NSString* title = @"long titlelong titlelong titlelong titlelong titlelong titlelong and another string titlelong titlelong title end";
NSAttributedString* str = [[[NSAttributedString alloc] initWithString:title attributes:paragraphStyle] autorelease];
NSMenuItem* newItem = [[NSMenuItem alloc] initWithTitle:title action:@selector(showWhitespaces:) keyEquivalent:@""];
[newItem setAttributedTitle:str];
[newItem setEnabled:YES];
[theMenu addItem:newItem];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow