我已经成功创建了一个 NSCollectionView 并向 IB 中的视图原型添加了一个标签,绑定到我所表示的对象的属性。我现在想以编程方式创建一个 NSButton 和 NSTextField,并将 NSTextField 绑定到我所表示的对象的属性。单击按钮时我想显示和隐藏 NSTextField。
我遇到的问题是,如果我将控件的初始化代码放在视图的 initWithCoder 方法中,并将绑定放在视图的 awakeFromNib 中,则绑定不会连接起来。如果我将控件的初始化放在 awakeFromNib 中,则单击按钮时,我无权访问视图中的控件(使用 NSLog 打印时它们为空)。
据我所知,问题可能在于 NSCollectionView 的工作方式是,它创建视图的实例,然后复制它以了解集合视图中每个对象的数量。如何获取要初始化的按钮和与原型副本一起使用的绑定?
下面是我的初始化代码和子类视图的 awakeFromNib 中的绑定:
子视图.h
@interface SubView : NSView {
NSButton *button;
NSTextField *textField;
IBOutlet NSCollectionViewItem *item; // Connected in IB to my NSCollectionViewItem
}
- (IBAction)buttonClicked:(id)sender;
@end
子视图.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
这听起来与我刚刚所做的类似,所以也许这就是您所需要的。
子类NSCollectionView http://developer.apple.com/documentation/Cocoa/Reference/NSCollectionView_Class/Introduction/Introduction.html并覆盖:
- (NSCollectionViewItem *)newItemForRepresentedObject:(id)object
In 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
希望这离你需要去的地方很近......
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)