NSButton 不像 UIButton 那樣可以直接設(shè)置顏色郑临,需要自定義一個(gè)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