以编程方式创建视图和子视图

时间:2012-04-02 04:10:57

标签: objective-c xcode cocoa

我有以下代码以编程方式创建我的窗口,视图和子视图。问题是我的子视图“filterView2”在该行添加[filterView addSubview:filterView2];崩溃时。有没有我忘记包含或做错的事情?谢谢!

    NSRect mainFrame = [[NSScreen mainScreen] frame];
    NSRect helpFrame = NSZeroRect;
    float width = 600;
    float height = 400;
    helpFrame.origin.x = (mainFrame.size.width - width) / 2.0;
    helpFrame.origin.y = 260.0;
    helpFrame.size.width = width;
    helpFrame.size.height = height; 

    helpWindow2 = [[BrightnessView windowWithFrame:helpFrame] retain];

    // Configure window.
    [helpWindow2 setReleasedWhenClosed:YES];
    [helpWindow2 setHidesOnDeactivate:NO];
    [helpWindow2 setCanHide:NO];
    [helpWindow2 setCollectionBehavior:NSWindowCollectionBehaviorCanJoinAllSpaces];
    [helpWindow2 setIgnoresMouseEvents:YES];
    [helpWindow2 setBackgroundColor:[NSColor clearColor]];
    [helpWindow2 setOpaque:NO];


    // Configure contentView.
    NSView *filterView = [helpWindow2 contentView];
    [filterView setWantsLayer:YES];
    //add subview
    NSView *filterView2 = [helpWindow2 contentView];
    [filterView addSubview:filterView2];

    //CALayer for filterView
    CALayer *theLayer = [CALayer layer];
    theLayer.opacity = 0;
    [filterView setLayer:theLayer];
    CGColorRef bgColor = CGColorCreateGenericRGB(0, 200, 255, 1);
    theLayer.backgroundColor = bgColor;
    CGColorRelease(bgColor);
    theLayer.borderColor = CGColorGetConstantColor(kCGColorWhite);
    theLayer.cornerRadius = 8.0;

    float helpOpacity = (([NSApp isActive] ? 1 : 0));
    [[[helpWindow2 contentView] layer] setOpacity:helpOpacity];


    [window addChildWindow:helpWindow2 ordered:NSWindowAbove];

1 个答案:

答案 0 :(得分:2)

我认为filterViewfilterView2是同一个对象,会导致异常。您无法将视图添加为自身的子视图。