objective-c - 以编程方式创建 View 和 subview

标签 objective-c xcode cocoa

我有以下代码以编程方式创建我的窗口、我的 View 和我的 subview 。问题是我的 subview “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];

最佳答案

我认为filterViewfilterView2是同一个对象,这会导致异常。您不能添加 View 作为其自身的 subview 。

关于objective-c - 以编程方式创建 View 和 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9970812/

相关文章:

iphone - 使用自己的按钮(不是预定义的按钮)创建自己的 UI。它们是什么类型的物体?

objective-c - iOS 中 MKMapView 的自定义图钉?

swift - 基于 Swift 的应用程序可以在 OS X 10.9/iOS 7 及更低版本上运行吗?

ios - 格式字符串未使用数据参数?

iOS代码覆盖率: @implementation Not Hit?

cocoa - 使用 Cocoa 的 Accessibility API 获取应用程序的 Dock 图标的位置

ios - UIPanGestureRecognizer 和 UIPinchGestureRecogizer 用于放大和移动弹回动画

ios - 将视频帧的长宽比转换为屏幕尺寸

ios - SecItemAdd 和 SecItemCopyMatching 返回错误代码 -34018 (errSecMissingEntitlement)

objective-c - 如何在 NSTextView 中设置字体?