2012-03-25 42 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