NSButton 设置背景颜色

NSButton 不像 UIButton 那样可以直接设置颜色,需要自定义一个NSButton类,重写drawRect:方法

- (void)drawRect:(NSRect)dirtyRect 

    [super drawRect:dirtyRect]; 

    //背景颜色 

    [[NSColor blueColor] set]; 

    NSRectFill(self.bounds); 


    //绘制文字 

    if (titleString != nil) { 

        NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init]; 

        [paraStyle setParagraphStyle:[NSParagraphStyle defaultParagraphStyle]]; 

        [paraStyle setAlignment:NSCenterTextAlignment]; 

        //[paraStyle setLineBreakMode:NSLineBreakByTruncatingTail]; 

        NSDictionary *attrButton = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Verdana" size:14], NSFontAttributeName, [NSColor colorWithCalibratedRed:255 green:255 blue:255 alpha:1], NSForegroundColorAttributeName, paraStyle, NSParagraphStyleAttributeName, nil]; 

        NSAttributedString * btnString = [[NSAttributedString alloc] initWithString:titleString attributes:attrButton]; 


        [btnString drawInRect:NSMakeRect(0, 4, self.frame.size.width, self.frame.size.height)]; 

    } 

}

注:不绘制文字的话文字就不会显示


参考资料:http://www.cocoachina.com/bbs/read.php?tid=271752

你可能感兴趣的:(NSButton 设置背景颜色)