NSMenuItem toggle粗体字体样式

时间:2013-04-05 10:02:10

标签: objective-c cocoa osx-lion nsmenuitem

我必须实现NSMenuItem,这样选择的NSMenuItem应该有Bold Text,这就是我所做的,

@implementation NSMenuItem (Font)

-(void)setBoldStyle:(bool)bBold{
    NSString* title = [self title] ;

    NSFont *pFont = (bold)?[NSFont boldSystemFontOfSize:14]:[NSFont menuFontOfSize:12];

    NSDictionary* fontAttribute = [NSDictionary dictionaryWithObjectsAndKeys:
                                   pFont, NSFontAttributeName,
                                   nil] ;

    NSMutableAttributedString* newTitle = [[NSMutableAttributedString alloc] initWithString:title
                                                                                 attributes:fontAttribute] ;

    [self setAttributedTitle:newTitle] ;
    [newTitle release] ;

}

@end

使用以上代码,我可以在选择特定的NSMenuItem时设置粗体文本, 但是如果它需要切换(意味着如果一个项目之前是粗体,那么现在应该是正常的),那么它就不会发生,

这就是我称之为的方式,

    // have we selected any menuitem yet
    if ( prevStatusIndex >0){
        // then deselect it
        pTempMenuItem = [pMenu itemAtIndex:prevStatusIndex];
        [pTempMenuItem setBoldStyle:NO];
    }

    prevStatusIndex = clientStatus+1;
    pTempMenuItem = [pMenu itemAtIndex:prevStatusIndex]; // 1 because a separator added
    [pTempMenuItem setBoldStyle:YES];

任何想法都会出错?

2 个答案:

答案 0 :(得分:0)

您需要使用与此相似的内容:

if ([pTempMenuItem boldStyle]) {
    NSLog(@"currently bold. change it");
    [pTempMenuItem setBoldStyle:NO]);
}
else{
    [pTempMenuItem setBoldStyle:YES]);
    NSLog(@"currenlty normal. change it");
}

答案 1 :(得分:0)

我们只能猜测,因为您的问题中缺少大量信息 - prevStatusIndexpMenuItempMenuclientStatus已声明和给定值? clientStatus的有效范围是多少?等

在评论中,您说过您已经使用过调试器和断点,但没有说明您看到了什么值。

你真的需要提供更多细节,以便民间可以帮助你。

提供所选索引永远不为0(即prevStatusIndex不为0或clientStatus不为-1)并且pMenu指向正确的菜单然后你的代码有效。如果所选索引可以为零,那么您需要将用于去除粗体的测试更改为prevStatusIndex >= 0,否则菜单中的第一个条目可以加粗但不会被取消。

HTH。

相关问题