NSMenuItem:Truncation和setLineBreakMode

时间:2012-03-25 11:28:54

标签: objective-c cocoa truncate nsmenuitem

我正在以编程方式创建几个菜单项:

    NSMenuItem* newItem = [[NSMenuItem alloc] initWithTitle:t action:s keyEquivalent:e];
    [newItem setTarget:target];
    [newItem setEnabled:YES];

    [self addItem:newItem];

我想截断它们的内容(在中间):

  

一些真正很长的冠军--->一些rea ... title

我读过关于使用setLineBreakMode方法的内容......但是如何?(我认为我做错了什么:-S)

1 个答案:

答案 0 :(得分:4)

可能的解决方案是使用NSAttributedString和[NSMenuDelegate confinementRectForMenu:onScreen:screen];

confinementRectForMenu是设置所需的最大宽度所必需的

为了向您展示一个没有委托的示例,我展示了一个非常大字体的菜单项

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];