如何在我的NSCollectionView的视图子类中以编程方式绑定?

Aus*_*tin 4 cocoa binding objective-c nscollectionview

我已成功创建了一个NSCollectionView,并在IB中的视图原型中添加了一个标签,绑定到我所代表的对象的属性.我现在想以编程方式创建一个NSButton和NSTextField,其中NSTextField绑定到我表示的对象的属性.单击按钮时,我想显示并隐藏NSTextField.

我遇到的问题是,如果我在视图的initWithCoder方法中为控件添加初始化代码,并且在视图的awakeFromNib中绑定,则绑定不会被连接起来.如果我将我的控件的初始化放在awakeFromNib中,当单击该按钮时,我无法访问视图中的控件(使用NSLog打印时它们为null).

从我可以告诉它看起来问题可能是NSCollectionView的工作方式是,它创建了一个视图实例,然后复制它以了解集合视图中的每个对象的方式.如何获取初始化按钮和绑定以使用原型的副本?

下面是我的初始化代码和我在子类视图的awakeFromNib中的绑定:

SubView.h

@interface SubView : NSView {
    NSButton *button;
    NSTextField *textField;
    IBOutlet NSCollectionViewItem *item; // Connected in IB to my NSCollectionViewItem
}

- (IBAction)buttonClicked:(id)sender;

@end
Run Code Online (Sandbox Code Playgroud)

SubView.m

@implementation SubView

- (id)initWithCoder:(NSCoder *)decoder
{
    id view = [super initWithCoder:decoder];

    button = [[NSButton alloc] initWithFrame:NSMakeRect(50, 95, 100, 20)];
    [button setTitle:@"Begin Editing"];
    [button setTarget:self];
    [button setAction:@selector(buttonClicked:)];
    [self addSubview:button];

    textField = [[NSTextField alloc] initWithFrame:NSMakeRect(10, 10, 100, 75)];
    [self addSubview:textField];

    return(view);
}

- (void)awakeFromNib
{   
        // Bind the textField to the representedObject's name property
        [textField bind:@"value" 
       toObject:item 
        withKeyPath:@"representedObject.name" 
        options:nil];
}

- (IBAction)buttonClicked:(id)sender
{
    [button setTitle:@"End Editing"];
    [textField setHidden:YES];
}

@end
Run Code Online (Sandbox Code Playgroud)

小智 12

这听起来类似于我刚刚做的事情,所以也许这就是你所需要的.

子类NSCollectionView和覆盖:

- (NSCollectionViewItem *)newItemForRepresentedObject:(id)object
Run Code Online (Sandbox Code Playgroud)

newItemForRepresentedObject:,检索视图项,然后添加您的控件和任何编程绑定:

@implementation NSCollectionViewSubclass

- (NSCollectionViewItem *)newItemForRepresentedObject:(id)object {

    // Allow the superclass to create or copy the collection view item
    NSSCollectionViewItem *newItem = [super newItemForRepresentedObject:object];

    // Get the new item's view so you can mess with it
    NSView *itemView = [newItem view];

    //
    // add your controls to the view here, bind, etc
    //

    return newItem;
}

@end
Run Code Online (Sandbox Code Playgroud)

希望这是一个接近你需要的地方......