如何获得父控件属性?

时间:2014-10-17 07:06:49

标签: objective-c macos cocoa

我正在尝试以编程方式生成一组类似的控件并将事件绑定到它们。事件逻辑将相对于几个控件属性创建。所以,我写了这个:

// Create zero root folder controls
for (SubFolderType* subFolder in rootFolder.subFolders)
    {
        FolderControl* folderControl = [[FolderControl alloc] initWithNibName:@"FolderControl" bundle:nil type:subFolder.type title:subFolder.name rootLevel:0];

        // positioning
        [folderControl view].frame = CGRectMake(30, 200 - iterator*40, 250, 40);
        [folderControl view].wantsLayer = YES;
        [[folderControl view] setShadow:shadow];
        [folderControl view].layer.backgroundColor = [[NSColor whiteColor] CGColor];
        // bind to self and add action
        [folderControl.DiclosureControl setTarget:self];
        [folderControl.DiclosureControl setAction:@selector(DiclosureControl_Click:)];

        // add to view as subview
        [dialogControl.view addSubview:[folderControl view]];
        iterator++;
    }

FolderControl是一个自定义控件,它有几个属性,如title或rootLevel。该事件被绑定到公开三角形,它应该生成下一个根级别的控件。

所以看起来像:

- (IBAction) DiclosureControl_Click : (NSButton*) sender {
    // How to get folderControl properties here?
    NSView *parentView = [sender superview]; // That's a NSView object, how can I get FolderControl type, which is NSViewController?
    // generate the next level of controls
}

问题是,发送者是一个双关闭按钮,它是一个简单的NSButton。如何在此处获取父控件(FolderControl)属性?

据我所知,根据this questionthis one,我无法直接使用setAction传递参数。如何解决这个问题?


更新:

所以,我在DiclosureControl_Click事件中犯了一个错误,认为发件人是FolderButton类型,而它只是一个按钮。我已经改写并更新了这个问题。

1 个答案:

答案 0 :(得分:1)

Preatty确保如果你不将FolderControl个实例存储在任何地方,它们将被释放,因为视图没有对视图控制器的强引用。

所以改变你的代码,这样你不仅可以:

[dialogControl.view addSubview:[folderControl view]];

但是某种或:

[dialogControl.folderControllers addObject:folderControl];

这样你就可以:

folderController.DiclosureControl.tag = [dialogControl.folderControllers indexOfObject:folderControl];

...
- (IBAction) DiclosureControl_Click : (NSButton*) sender {
   FolderController *controller = dialogControl.folderControllers[sender tag]; 
   ...
}