如何将NSButton添加到CALayer?

时间:2015-02-04 07:27:48

标签: cocoa calayer ikimagebrowsercell

我正在尝试在IKImageBrowserCell对象内的图层上添加NSButton。我发现this帖子很有帮助,但它并没有进入关键时刻。 我已经尝试过了:

- (CALayer *) layerForType:(NSString*) type
{
    CGColorRef color;

    //retrieve some usefull rects
    NSRect frame = [self frame];
    NSRect imageFrame = [self imageFrame];
    NSRect relativeImageFrame = NSMakeRect(imageFrame.origin.x - frame.origin.x, imageFrame.origin.y - frame.origin.y, imageFrame.size.width, imageFrame.size.height);

    /* foreground layer */
    if(type == IKImageBrowserCellForegroundLayer){
        //no foreground layer on place holders
        if([self cellState] != IKImageStateReady)
            return nil;

        //create a foreground layer that will contain several childs layer
        CALayer *layer = [CALayer layer];
        layer.frame = CGRectMake(0, 0, frame.size.width, frame.size.height);


        //add a checkbox to tell whether to upload this one or not
        NSRect checkFrame  = NSMakeRect( ( frame.size.width/2)-5 , frame.size.height - 19, 18,18);
        NSButton *uploadCheckBox = [[NSButton alloc] initWithFrame:checkFrame];
        [uploadCheckBox setButtonType:NSSwitchButton];
        [layer addSublayer :[uploadCheckBox layer]];

        return layer;
    }
    //(...)
    return nil;
}

但不幸的是,按钮没有出现在图层上。我认为按钮的位置很好,因为它基于Apple应用程序的示例代码。我觉得这条线路错了: layer addSublayer :[uploadCheckBox layer]];,因为我应该添加整个NSButton,而不仅仅是它的位图表示(一个层)。任何帮助非常感谢!

1 个答案:

答案 0 :(得分:0)

您无法在CALayer中添加NSView。您应该为按钮目的创建一个新图层并添加到保留图层。