2013-03-18 3 views
0

Я пытаюсь создать подкласс NSButton, который также использует подкласс NSButtonCell, но я не могу это сделать в коде!Как программно выделить подкласс NSButton с помощью пользовательского NSButtonCell?

Это мой NSButonCell подкласс, что это хорошо работает, если я создаю кнопку в IB и установить свой класс клеток непосредственно в IB:

#import "MyCustomCell.h" 

@implementation MyCustomCell 

- (void)drawImage:(NSImage*)image withFrame:(NSRect)frame inView:(NSView*)controlView 
{ 
    NSGraphicsContext *ctx = [NSGraphicsContext currentContext]; 
    CGContextRef contextRef = [ctx graphicsPort]; 

    NSData *data = [image TIFFRepresentation]; 
    CGImageSourceRef source = CGImageSourceCreateWithData((CFDataRef)data, NULL); 
    if(source) { 
     CGImageRef imageRef = CGImageSourceCreateImageAtIndex(source, 0, NULL); 
     CFRelease(source); 

     CGContextSaveGState(contextRef); 
     { 
      NSRect rect = NSOffsetRect(frame, 0.0f, 1.0f); 
      CGFloat white = [self isHighlighted] ? 0.2f : 0.35f; 
      CGContextClipToMask(contextRef, NSRectToCGRect(rect), imageRef); 
      [[NSColor colorWithDeviceWhite:white alpha:1.0f] setFill]; 
      NSRectFill(rect); 
     } 
     CGContextRestoreGState(contextRef); 

     CGContextSaveGState(contextRef); 
     { 
      NSRect rect = frame; 
      CGContextClipToMask(contextRef, NSRectToCGRect(rect), imageRef); 
      [[NSColor colorWithDeviceWhite:0.1f alpha:1.0f] setFill]; 
      NSRectFill(rect); 
     } 
     CGContextRestoreGState(contextRef);   

     CFRelease(imageRef); 
    } 
} 

- (void)drawBezelWithFrame:(NSRect)frame inView:(NSView *)controlView 
{ 
    NSGraphicsContext *ctx = [NSGraphicsContext currentContext]; 

    CGFloat roundedRadius = 3.0f; 

    BOOL outer = YES; 
    BOOL background = YES; 
    BOOL stroke = YES; 
    BOOL innerStroke = YES; 

    if(outer) { 
     [ctx saveGraphicsState]; 
     NSBezierPath *outerClip = [NSBezierPath bezierPathWithRoundedRect:frame xRadius:roundedRadius yRadius:roundedRadius]; 
     [outerClip setClip]; 

     NSGradient *outerGradient = [[NSGradient alloc] initWithColorsAndLocations: 
           [NSColor colorWithDeviceWhite:0.20f alpha:1.0f], 0.0f, 
           [NSColor colorWithDeviceWhite:0.21f alpha:1.0f], 1.0f, 
           nil]; 

     [outerGradient drawInRect:[outerClip bounds] angle:90.0f]; 
     [outerGradient release]; 
     [ctx restoreGraphicsState]; 
    } 

    if(background) { 
     [ctx saveGraphicsState]; 
     NSBezierPath *backgroundPath = [NSBezierPath bezierPathWithRoundedRect:NSInsetRect(frame, 2.0f, 2.0f) xRadius:roundedRadius yRadius:roundedRadius]; 
     [backgroundPath setClip]; 

     NSGradient *backgroundGradient = [[NSGradient alloc] initWithColorsAndLocations: 
             [NSColor colorWithDeviceWhite:0.17f alpha:1.0f], 0.0f, 
             [NSColor colorWithDeviceWhite:0.20f alpha:1.0f], 0.12f, 
             [NSColor colorWithDeviceWhite:0.27f alpha:1.0f], 0.5f, 
             [NSColor colorWithDeviceWhite:0.30f alpha:1.0f], 0.5f, 
             [NSColor colorWithDeviceWhite:0.42f alpha:1.0f], 0.98f, 
             [NSColor colorWithDeviceWhite:0.50f alpha:1.0f], 1.0f, 
             nil]; 

     [backgroundGradient drawInRect:[backgroundPath bounds] angle:270.0f]; 
     [backgroundGradient release]; 
     [ctx restoreGraphicsState]; 
    } 

    if(stroke) { 
     [ctx saveGraphicsState]; 
     [[NSColor colorWithDeviceWhite:0.12f alpha:1.0f] setStroke]; 
     [[NSBezierPath bezierPathWithRoundedRect:NSInsetRect(frame, 1.5f, 1.5f) xRadius:roundedRadius yRadius:roundedRadius] stroke]; 
     [ctx restoreGraphicsState]; 
    } 

    if(innerStroke) { 
     [ctx saveGraphicsState]; 
     [[NSColor colorWithDeviceWhite:1.0f alpha:0.05f] setStroke]; 
     [[NSBezierPath bezierPathWithRoundedRect:NSInsetRect(frame, 2.5f, 2.5f) xRadius:roundedRadius yRadius:roundedRadius] stroke]; 
     [ctx restoreGraphicsState];   
    } 

    if([self isHighlighted]) { 
     [ctx saveGraphicsState]; 
     [[NSBezierPath bezierPathWithRoundedRect:NSInsetRect(frame, 2.0f, 2.0f) xRadius:roundedRadius yRadius:roundedRadius] setClip]; 
     [[NSColor colorWithCalibratedWhite:0.0f alpha:0.35] setFill]; 
     NSRectFillUsingOperation(frame, NSCompositeSourceOver); 
     [ctx restoreGraphicsState]; 
    } 
} 

@end 

Я также создать пользовательские NSButton sublclass, которые используют этот NSButtonCell

#import "myButton.h" 
#import "MyCustomCell.h" 

@implementation myButton 

- (id)initWithFrame:(NSRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) 
    { 
     [self setCell:[[MyCustomCell alloc] init]]; 
     self.image = [NSImage imageNamed:@"add"]; 

    } 

    return self; 
} 

@end 

Но когда я создаю эту кнопку, на мой взгляд, кнопка выглядит по умолчанию, а не настраиваемый стиль подкласса NSButtonCell. Если я устанавливаю ячейку в IB, все работает отлично, но не в коде. У кого-нибудь есть идея решить эту проблему? Благодаря!

+0

Вы пробовали -initWithNibName: bundle: для инициализации MyCustomCell в вашем коде, например [self setCell: [[MyCustomCell alloc] initinitWithNibName: @ "nibName" bundle: nil]]; ? –

+0

Я не хочу использовать nib o xib. Я не хочу выделять все в коде – Luca

+0

Когда вы устанавливаете точку останова в своем классе myButton, вызывает ли '-initWithFrame:' ​​вызов? Кажется, это должно работать нормально. – gaige

ответ

1

Я понимаю, как исправить эту проблему.

Необходимо установить стиль рамки на кнопку setBezelStyle. С этой строкой кода все отлично работает, за исключением того, что изображение перевернуто.

0

Вы пытались использовать метод класса cellClass?

+ (Class)cellClass { 
    return MyCustomCell.class; 
} 
+0

Да, я также попытался использовать метод cellClass, но до сих пор не работает! Кажется, единственное решение - использовать XIB-файл, но это действительно странная ситуация: должно быть возможно сделать это с помощью кода. – Luca

 Смежные вопросы

  • Нет связанных вопросов^_^