2012-03-25 56 views
1

我编程方式创建的菜单项,像这样:NSMenuItem:截断和setLineBreakMode

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

    [self addItem:newItem]; 

我要截断其内容(中)这样的:

有些真的长标题--->一些原因...标题

我读过关于使用setLineBreakMode方法...但是如何?(我觉得我做错了什么:-S)

回答

4

一个可能的解决方案包括使用NSAttributedString和[NSMenuDelegate confinementRectForMenu:屏幕:屏幕]。

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

我碰到了同样的解决方案来(像往常一样:发布问题后),但我有问题设置菜单项的宽度。非常感谢你指出了这一点;我会看看它; ;-) – 2012-03-25 14:27:40